简体   繁体   English

Python - 以非线性方式运行循环

[英]Python - run through a loop in non linear fashion

SO, I am searching for a way to loop through a list of items in a for loop fashion, except I want the loop to iterate in a 'random' way. 所以,我正在寻找一种以循环方式循环遍历项目列表的方法,除了我希望循环以“随机”方式迭代。 ie I dont want the loop to go 0,1,2,3,m+1...n, I want it to pick it in some random order and still run through the loop for all items. 即我不希望循环进入0,1,2,3,m + 1 ... n,我希望它以一些随机顺序选择它并仍然运行所有项目的循环。

Here is my current looping code: 这是我目前的循环代码:

for singleSelectedItem in listOfItems:
  item = singleSelectedItem.databaseitem
  logging.info(str(item))    

please let me know if this doesnt make sense ;) 如果这没有意义,请告诉我;)

If listOfItems can be shuffled, then 如果listOfItems可以改组,那么

import random
random.shuffle(listOfItems)
for singleSelectedItem in listOfItems:
    blahblah

otherwise 除此以外

import random
randomRange = range(len(listOfItems))
random.shuffle(randomRange)
for i in randomRange:
    singleSelectedItem = listOfItems[i]
    blahblah

Edit for Jochen Ritzel's better approach in the comment. 编辑Jochen Ritzel在评论中的更好方法。
The otherwise part can be 否则部分可以

import random
for item in random.sample(listOfItems, len(listOfItems))
    blahblah
import random
random.shuffle(listOfItems)

for singleSelectedItem in listOfItems:
  item = singleSelectedItem.databaseitem
  logging.info(str(item))

好吧,如果性能不是很重要,你可以随便洗牌,或者如果那些必须保持相同的顺序,创建一个所有indizes和shuffle的列表(例如indizes = range(len(listOfItems)),random.shuffle( indizes))

>>> lst = ['a', 'b', 'c', 'd']
>>> nums = list(range(0, len(lst)))
>>> import random
>>> random.shuffle(nums)
>>> for i in nums:
...     print lst[i]
c
a
b
d

Or if the list is really large you can use a bit of generator flavoring. 或者,如果列表非常大,您可以使用一些生成器调味。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM