使用 itertools 的配方。您需要使用来自 itertools 页面 here 的 roundrobin 配方,下面也有重复:
from itertools import islice, cycle, repeat
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
# Now, the real recipe starts
obj = {'a1':3,'a2':5,'a3':1}
objiter = [repeat(x,y) for x,y in obj.items()]
objlist = list(roundrobin(*objiter))
objlist
['a1', 'a3', 'a2', 'a1', 'a2', 'a1', 'a2', 'a2', 'a2']
请注意,这并没有准确地为您提供所需的内容...正如其他答案之一所说,您可以使用字典的排序版本(也包括在下面),或者您可以使用 OrderedDict首先。请记住,如果您使用 OrderedDict 并将其初始化为 my_odict = OrderedDict({1:1, 2:2, 3:3}),python 将首先创建字典 - 无序 - 然后从中创建 OrderedDict,这可能不是您想要的。
排序:
objiter = [repeat(x, obj[x]) for x in sorted(obj.keys())]
objlist = list(roundrobin(*objiter))
objlist
['a1', 'a2', 'a3', 'a1', 'a2', 'a1', 'a2', 'a2', 'a2']
很明显,有序字典recipe和普通字典recipe是一样的,只是传入一个有序字典。