2016-07-06 74 views
-1

說我有像這樣一本字典:是否可以將列表字典合併到一個列表中?

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

我怎麼能結合所有列出了本字典成一個大名單中的一行代碼(意思是不會有一個臨時變量)?我想出了以下解決方案,但它不是很優雅:

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他在他編碼的最後一行做了 – 2016-07-06 11:28:43

+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 

reduce大約是兩倍的速度itertools。對於較大的結構來說也是如此。

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

這應該這樣做:

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

刪除sorted如果你的結果並不需要是排序

1

您可以使用itertools

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

是的,但你爲什麼?如果您立即將迭代器用到列表中,您不會從'itertools'獲得太多好處! – jonrsharpe

相關問題