[英]List index out of range after using shuffle function in Python
重要的是要让读者知道,有时我必须在调用 function 之前删除列表中的项目。
Traceback (most recent call last):
File "C:\Users\User\Desktop\permdebunk.py", line 195, in <module>
shuff(c,len(c))
File "C:\Users\User\Desktop\permdebunk.py", line 181, in shuff
c[i],c[j] = c[j],c[i]
IndexError: list index out of range
如果 Python 的random.shuffle()
不能执行所有可能的排列,它就不足以满足我的需要。 所以我做了一些谷歌搜索,发现这个 function 对一个列表进行了洗牌,据说可以规避上述关于 Python 的random.shuffle()
的问题
def shuff(c, n):
for i in range(n-1,0,-1):
random.seed()
j = random.randint(0,i+1)
c[i],c[j] = c[j],c[i]
问题似乎发生在我 append c[0]
到c
然后 del c[0]
推入列表之后。 我有超过 200 多行代码作为 NP 难题的实验。 请查看链接中的第一个日志。 记得检查第 195 和 181 行
编辑:链接没有行号,所以使用ctrl + f来查找单词 shuff
我可以通过哪些方式“推入”列表而不会出现任何索引错误? 而且,为什么 python 会抛出该错误?
random.randint()
包括两个端点。 因此,当i = n - 1
时, randint(0, i + 1)
可以返回(n - 1) + 1
,即n
。 c[n]
超出列表范围。
我应该认为将randint()
调用更改为randint(0, i)
应该可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.