我正在尝试创建一个程序,该程序能够获取姓名列表并创建所有可能发生的个人对决。
代码还没有完全完成。
当我尝试调用函数时,我不断收到错误消息
list index is out of range for line 7, aka "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
最佳答案
标准库 itertools
模块有一个名为 combinations()
的函数,它可以执行您的请求(从可迭代项生成所有可能项目组合的列表)。如果你正在寻找排列,也就是说,如果 (A,B)
应该被视为不同于 (B,A)
,那么你会想要使用 排列()
。
例如,运行以下代码:
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')]
附带说明,恰好还有 an example使用 itertools 函数 islice()
和 cycle()
。但是术语“轮询”并不能准确描述您要执行的操作。您的问题的更好标题是“在 Python 中生成组合”或类似的标题。
关于Python 循环法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54601832/