我在用Python去除重复项,怎么才能实现?

编程语言 2026-07-09

我在做一个信任进化模拟器,但在试运行时,它突然弹出

[['e', 'n'], ['n', 'e'], ['n', 'tft'], ['tft', 'n']]

[['e', 'n',], ['n', 'tft'], ['tft', 'e']]

你知道怎么修复吗?

问题在这里:

players = ['tft','n','e']
batles = []
for i in players:
    for j in players:
        batles.append([i,j])
batles.sort()
print(batles)
for i in batles:
    for j in batles:
        if i == j:
            batles.remove(i)
print(batles)

解决方案

你会希望每位玩家与其他每位玩家都只对战一次,且没有人和自己对战。

就像这样:

players = ['tft', 'n', 'e']
batles = []

# Use a tracking index to ensure players only match with players after them
for index, i in enumerate(players):
    for j in players[index + 1:]:
        batles.append([i, j])

batles.sort()
print(batles)

输出:

[['e', 'n'], ['n', 'tft'], ['tft', 'e']]

这条线 players[index + 1:] 将确保一旦某位玩家被匹配,他们再也不会与之前的对手再次匹配。

这将防止如 ['n', 'e']['e', 'n'] 这样的重复情况再也不会形成。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章