Python随机无重复 [英] Python Random's with no repeats
本文介绍了Python随机无重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码,我试图用0-6之间的7个数字填充列表,没有重复,并且每次都随机排列.这是我的代码,但是我不断收到错误列表分配索引超出范围",但是我看不到我的错误在哪里.这是我的代码:
Here is my code, im trying to fill a list with 7 numbers between 0-6 with no duplicates, and a random order every time. Here is my code but I keep getting an error "list assignment index out of range", I don't see where my error is though. Here is my code:
import random
def generate():
listA = []
for x in range(0,6):
listA[x] = random.sample(range(6), 1)
generate()
print(listA)
推荐答案
仅对 range
的结果进行 shuffle
会更有效.
It'd be more effective to just shuffle
the result of range
.
>>> from random import shuffle
>>>
>>> r = range(7)
>>> shuffle(r)
>>> r
[5, 3, 6, 4, 1, 0, 2]
请注意,在Python 3中,您必须将 r
明确转换为列表:
Note that in Python 3 you have to explicitly convert r
to a list:
>>> r = list(range(7))
这篇关于Python随机无重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文