2016-07-06 7 views
-1

は、私はそうのような辞書を持っていると言う:リストの辞書を1つのリストにまとめることは可能ですか?

my_list = { 
    "foo": ["a", "b", "c"], 
    "bar": ["d", "e", "f"] 
} 

私は1行のコード(一時的な変数がないだろうという意味)内の1つの大きなリストにこの辞書内のすべてのリストを組み合わせることができどのように?私は、しかし、それは非常にエレガントではありません、以下の解決策を考え出した:私は、キーはプロセスで失われていることを気にしない

def combine_list_dictionary(): 
    temp = [] 
    for (key, value_list) in my_list: 
     temp += value_list 
    return temp 

combine_list_dictionary() # ["a", "b", "c", "d", "e", "f"] 

+0

「my_list」という名前の辞書があり、必要な出力を明示的にリストとして辞書として記述してください。 – jonrsharpe

+0

@jonrsharpe彼はコーディングの最後の行にしました –

+0

@jonrsharpe私の例の最後の行には、出力が – Paradoxis

答えて

2

リストに参加するのに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'] 
>>> 

は、小規模および大規模な辞書の両方のためのchainreduce間のパフォーマンスの比較です。

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

reduceitertoolsの約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 
+1

'sum 'の問題は、各ステップごとに新しいリストが作成されることです。潜在的に非効率的です。リストと辞書がそれほど大きくなければ、それは関係ないかもしれません。 – jonrsharpe

0

これは、実行する必要があります。あなたの結果はあなたはitertoolsを使用することができます

1

をソートする必要がない場合

result = sorted(sum(my_list.values(), [])) 

sortedを削除します。

import itertools 
combined_results = list(itertools.chain.from_iterable(my_list.values())) 
+0

はい、どうですか?イテレータをすぐにリストに使用すると、itertoolsから多くの利点を得ることはできません! – jonrsharpe

関連する問題