在python中分发一个列表

Har*_*rdy 3 python distribution

假设我有一个配置字典:

config = {'A': 3, 'B': 4, 'C': 2}
Run Code Online (Sandbox Code Playgroud)

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

result = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'B']
Run Code Online (Sandbox Code Playgroud)

另一个例子:

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

config = {'A': 2, 'B': 2}
result = ['A', 'B', 'A', 'B']
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 6

你可以使用这个itertools配方 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()))))
Run Code Online (Sandbox Code Playgroud)