リストに参加するのにsum
を使用しないでください。なぜそれが悪い考えであるのかについて、長い間、Pythonアイデアのメーリングリストに議論があります(リンクは後で得られます)。
itertools.chain
は良い解決策である、またはあなたではなく、機能に行くならば、ここで
>>> my_list = {
... "foo": ["a", "b", "c"],
... "bar": ["d", "e", "f"]
... }
>>> import operator as op
>>> reduce(op.concat, my_list.values())
['a', 'b', 'c', 'd', 'e', 'f']
>>>
は、小規模および大規模な辞書の両方のためのchain
とreduce
間のパフォーマンスの比較です。
>>> import random
>>> dict_of_lists = {k: range(random.randint(0, k)) for k in range(0, random.randint(0, 9))}
>>> %timeit list(itertools.chain.from_iterable(my_list.values()))
The slowest run took 12.72 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 995 ns per loop
>>> %timeit reduce(op.concat, my_list.values())
The slowest run took 19.77 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 467 ns per loop
reduce
itertools
の約2倍の速さです。それは大きな構造の場合にも当てはまります。
>>> dict_of_lists = {k: range(random.randint(0, k)) for k in range(0, random.randint(0, 9999))}
>>> %timeit list(itertools.chain.from_iterable(my_list.values()))
The slowest run took 6.47 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1 µs per loop
>>> %timeit reduce(op.concat, my_list.values())
The slowest run took 13.68 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 425 ns per loop
「my_list」という名前の辞書があり、必要な出力を明示的にリストとして辞書として記述してください。 – jonrsharpe
@jonrsharpe彼はコーディングの最後の行にしました –
@jonrsharpe私の例の最後の行には、出力が – Paradoxis