python - Python中的随机迭代

标签 python random for-loop

当您想按顺序遍历数字列表时,您将编写:

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/

相关文章:

javascript - 为什么innerHTML在for循环中不能正常工作?

python - pandas 使用 if/truth 语句将函数应用于数据框的列

python - GNU Radio OOT 模块 AttributeError : 'module' object has no attribute 'MME_cpp'

python - 从 python 访问 C 结构

python - 在 PNG 中编码二进制数据?

java - 如何执行 JButton Action 监听器一定次数

c# - 在 VB.NET 中使用非整数增量进行循环

android - 在 TextView 上显示项目数组

java - 如果最后一个条件失败,如何重新启动 do-while 循环?

mysql - 仅使用一个选择在随机排序的子查询上重写分组依据