我有一套我想随机执行的动作。其中一个操作在字典上迭代。我希望每次调用此操作时,字典都会迭代到字典的下一个位置,而不是第一个位置。你知道吗
如果我只需要一个值,我可以使用列表而不是字典,将索引列表保存在函数调用之外,并将列表的最后一个索引传递给函数。但我需要两个价值观,关键和价值。我可以使用两个列表,将键存储在一个列表中,将值存储在另一个列表中,将索引保存在函数调用之外,并在每次调用action\u two时传递最后一个索引,但也许有一种更简单的方法来使用字典,即保存字典以某种方式迭代的位置,这样我就不需要使用两个列表了?你知道吗
import random
import time
def action_one(): print "action 1"
def action_two():
diccionarios_grupos_ids = {
'580864492030176':'Rafaela Argentina',
'314744565339924':'Ventas Rafaelinas',
'976386572414848':'Ventas en Rafaela y Zona',
'157271887802087':'Rafaela Vende',
'77937415209':'Mas Poco Vendo',
'400258686677963':'Clasificados Rafaela',
'1708071822797472':'Vende Susana Roca Bella Italia Lehmann San Antonio Villa San Jose y Rafaela',
'639823676133828':'L@s Loc@s de las ofertas sunchales!!!!!!',
'686381434770519':'H&M Computacion',
'1489889931229181':'RAFAELA Compra/Venta',
'228598317265312':'Compra-Venta Rafaela',
'406571412689579':'Alta Venta'}
for key,value in diccionarios_grupos_ids.iteritems():
print key,value
# I want to iterate in the next position the next time action_two is called
break
def action_three(): print "action 3"
lista_acciones = [action_one,action_two,action_three]
while True:
tiempo_random = random.randint(1,3)
time.sleep(tiempo_random)
choice = random.choice(lista_acciones)
choice()
将
iteritem()
赋给变量,例如:您需要解决的问题是使用
iterable
来多次调用action_two()
最简单的是全局变量,但全局变量通常被认为是错误的样式:但是如果你只想要下一个,你可以用
next()
:可以使用生成器:
对
next(grupos_gen)
的每次调用都将提供一个后续的键/值对。你知道吗如果要循环浏览词典条目,可以使用
itertools.cycle
:有关更多信息,请查看Understanding Generators in Python
还要注意,
dict
不是有序的,因此不能保证您的键/值会以任何可复制的顺序进行迭代。如果这对您很重要,那么您应该使用OrderedDict。你知道吗相关问题 更多 >
编程相关推荐