我正在尝试创建一个程序,该程序能够列出名称并创建所有可能发生的个人对决。
代码尚未完全完成。
当我尝试调用函数
时,我不断收到错误消息列表索引超出第7行的范围,又称为“对于lst [c + 1:]中的s”。
有人可以帮我解释一下,也许更正吗?
谢谢。
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
答案 0 :(得分:4)
标准库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函数还可以进行an example的“循环”迭代(循环遍历一组可迭代对象,一次从每个迭代对象中提取一个,直到耗尽)。 islice()
和cycle()
。但是“轮循”一词并不能准确地描述您要做什么。对于您的问题,一个更好的标题是“在python中生成组合”或类似的东西。
答案 1 :(得分:0)
让我们看看您的代码:
import random
def pairShuffling(*names):
lst = list(names) # maximum allowed index for lst[idx]` will be in range 0..len(names)-1
lst2=[]
for c in range(len(names)): # `c` will be in range[0..len(names)-1]
if lst[c]!=lst[-1]:
for s in lst[c+1:]: # you overexceeding maximum allowed value for index
lst2 += [lst[c],lst[s]]
return lst2
我想您需要使用itertools.permutations或itertools.combinations
/ itertools.combinations_with_replacement