random iteration in Python

后端 未结 6 2095
南方客
南方客 2020-12-05 07:02

When you want to iterate sequentially over a list of numbers you will write:

for i in range(1000):
  # do something with i

But what if you

6条回答
  •  执笔经年
    2020-12-05 07:35

    Here's a different approach to iterating a list in random order. This doesn't modify the original list unlike the solutions that use shuffle()

    lst=['a','b','c','d','e','f']
    for value in sorted(lst,key=lambda _: random.random()):
        print value
    

    or:

    for value in random.sample(lst,len(lst)):
        print value
    

提交回复
热议问题