【发布时间】:2017-05-26 13:26:36
【问题描述】:
我有一组想要随机执行的操作。其中一个操作遍历字典。我希望每次调用此操作时,字典都会迭代到字典的下一个位置,而不是第一个位置。
如果我只需要一个值,我可以使用列表而不是字典,将索引列表保存在函数调用之外,并将列表的最后一个索引传递给函数。但我需要两个值,键和值。我可以使用 2 个列表,将键存储在一个列表中,将值存储在另一个列表中,将索引保存在函数调用之外,并在每次调用 action_two 时传递最后一个索引,但也许有一种更短的方法来使用字典通过保存字典以某种方式迭代的位置,我不需要使用 2 个列表?
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()
【问题讨论】:
-
一个示例输出会有所帮助。不清楚你在问什么。
-
以后需要列表的元素吗?如果不是,为什么不在引用它们后将它们从列表中删除并继续引用列表的第一个元素?
标签: python dictionary iteration