Python - 以非线性方式运行一个循环 [英] Python - run through a loop in non linear fashion
本文介绍了Python - 以非线性方式运行一个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种方法来循环通过for循环时尚的项目列表,除了我想循环以随机的方式进行迭代。即我不想循环去0,1,2,3,m + 1 ... n,我希望它以一些随机顺序选择,仍然运行所有项目的循环。
这里是我目前的循环代码:
对于listOfItems中的singleSelectedItem:
item = singleSelectedItem.databaseitem
logging.info(str(item))
请让我知道如果这没有意义的话)
解决方案
如果listOfItems可以被洗牌,那么
import random
random.shuffle(listOfItems)
for listOfItems中的singleSelectedItem:
blahblah
否则
导入随机
randomRange = range(len(listOfItems))
random.shuffle(randomRange)
for randomRange:
singleSelectedItem = listOfItems [i]
blahblah
编辑为Jochen Ritzel更好的方法在评论。
o可以是
import random
for item in random.sample(listOfItems,len(listOfItems))
blahblah
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. i.e. 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.
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
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.
The otherwise part can beimport random for item in random.sample(listOfItems, len(listOfItems)) blahblah
这篇关于Python - 以非线性方式运行一个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文