首页 > 解决方案 > 蟒蛇轮循

问题描述

我正在尝试创建一个能够获取名称列表并创建所有可能发生的个人对决的程序。

代码还没有完全完成。

当我尝试调用该函数时,我不断收到一条错误消息

列表索引超出第 7 行的范围,即“for s in lst[c+1:]”。

有人可以帮我解释一下并纠正它吗?

谢谢。

import random
def pairShuffling(*names):
    lst = list(names)
    lst2=[]
    for c in range(len(names)):
        if lst[c]!=lst[-1]:
            for s in lst[c+1:]:
                lst2 += [lst[c],lst[s]]
    return lst2

标签: pythonpython-3.6

解决方案


标准库itertools模块有一个调用的函数combinations() ,可以满足您的要求(从可迭代项中生成所有可能的项目组合的列表)。如果您正在寻找排列,也就是说,如果(A,B)应该被视为与 不同(B,A),那么您会想要使用permutations().

例如,运行以下代码:

from itertools import permutations, combinations

names = ['Jeff', 'Alice', 'Trogdor', 'Kublai Khan']

print("Combinations: ", [n for n in combinations(names, 2)])
print("Permutations: ", [n for n in permutations(names, 2)])

...将打印以下输出:

Combinations:  [('Jeff', 'Alice'), ('Jeff', 'Trogdor'), ('Jeff', 'Kublai Khan'), ('Alice', 'Trogdor'), ('Alice', 'Kublai Khan'), ('Trogdor', 'Kublai Khan')]
Permutations:  [('Jeff', 'Alice'), ('Jeff', 'Trogdor'), ('Jeff', 'Kublai Khan'), ('Alice', 'Jeff'), ('Alice', 'Trogdor'), ('Alice', 'Kublai Khan'), ('Trogdor', 'Jeff'), ('Trogdor', 'Alice'), ('Trogdor', 'Kublai Khan'), ('Kublai Khan', 'Jeff'), ('Kublai Khan', 'Alice'), ('Kublai Khan', 'Trogdor')]

附带说明一下,恰好还有一个使用 itertools 函数islice()cycle(). 但是“循环”一词并不能准确地描述您要做什么。你的问题的一个更好的标题是“在 python 中生成组合”,或者类似的东西。


推荐阅读