gpt4 book ai didi

python - 在 python 中分发列表

转载 作者:太空宇宙 更新时间:2023-11-03 12:33:07 25 4
gpt4 key购买 nike

假设我有一个配置字典:

config = {'A': 3, 'B': 4, 'C': 2}

我如何像这样扁平分布(散布)列表:(一个一个追加到结果列表仍然是所有配置的结尾)

result = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'B']

另一个例子:

config = {'A': 3, 'B': 1}
result = ['A', 'B', 'A', 'A']

config = {'A': 2, 'B': 2}
result = ['A', 'B', 'A', 'B']

最佳答案

您可以使用 itertools recipe roundrobin 为此:

from itertools import cycle, islice

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))

result = list(roundrobin(*(k * v for k, v in sorted(config.items()))))

关于python - 在 python 中分发列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23265468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com