当您想按顺序遍历数字列表时,您将编写:
for i in range(1000):
# do something with i
但是,如果您想随机遍历 (0..999) 范围内的数字列表怎么办?需要(在每次迭代中)随机选择在任何先前迭代中未选择的数字,并且需要迭代范围 (0..999) 中的所有数字。
你知道怎么做吗(聪明)?
最佳答案
您可以使用 random.shuffle()
到,好吧,洗牌:
import random
r = list(range(1000))
random.shuffle(r)
for i in r:
# do something with i
顺便说一句,在许多情况下,您会在其他编程语言中对一系列整数使用 for
循环,您可以直接描述要在 Python 中迭代的“事物”。
例如,如果你想使用 i
的值来访问列表的元素,你最好直接打乱列表:
lst = [1970, 1991, 2012]
random.shuffle(lst)
for x in lst:
print x
注意:在使用 random.shuffle()
时应牢记以下警告(取自 docs:
Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated.
关于python - Python中的随机迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9252373/