python - 蟒蛇轮循
问题描述
我正在尝试创建一个能够获取名称列表并创建所有可能发生的个人对决的程序。
代码还没有完全完成。
当我尝试调用该函数时,我不断收到一条错误消息
列表索引超出第 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
解决方案
标准库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 中生成组合”,或者类似的东西。
推荐阅读
- reactjs - history.push 不是函数
- r - 在 for 循环中重新编码几个变量
- python-3.x - Pandas 优化了值的查找
- php - 如何在国家下拉列表中显示选定的值
- extjs - 应用程序崩溃:Java 运行时环境检测到致命错误:[libsystem_platform.dylib+0x15d2] _platform_strlen+0x12
- java - Corretto 11 上的 AWS Elastic Beanstalk Tomcat 8.5 无法连接到 AWS 服务
- visual-studio - 如何为 WinForms 桌面应用程序的 URL 安装托管 MSIX 包
- python - XML 属性值无法匹配我的另一个字典的键,因此我无法替换属性值
- php - 是什么 || 符号在 Preg_replace() PHP 中的意思
- reactjs - React Formik Mui TextField 与自定义输入失去焦点