2017-08-03 104 views
0

是否可以將字典中的列表組合到一個新的密鑰中? 例如,我有一個字典設置Python,在字典中組合列表

ListDict = { 
    'loopone': ['oneone', 'onetwo', 'onethree'], 
    'looptwo': ['twoone', 'twotwo', 'twothree'], 
    'loopthree': ['threeone', 'threetwo', 'threethree']} 

我想了一個名爲「loopfour」包含從「loopone」,「looptwo」名單和「loopthree」新鍵

因此其名單將看起來像

['oneone', 'onetwo', 'onethree', 'twoone', 'twotwo', 'twothree', 'threeone', 'threetwo', 'threethree'] 

,並可以使用ListDict [ '四']調用和返回組合列表

+2

'ListDict [ 'loopfour'] = [el for l in ListDict.values()for el in l]'。 –

+2

列表是可變的。你想如何處理列表中的值更改的情況? – Alexander

回答

0

您可以使用itertools.chain.from_iterableimport itertools第一)(感謝juanpa.arrivillaga的改進):

In [1125]: ListDict['loopfour'] = list(itertools.chain.from_iterable(ListDict.values())) 
     ...: 

In [1126]: ListDict 
Out[1126]: 
{'loopfour': ['twoone', 
    'twotwo', 
    'twothree', 
    'threeone', 
    'threetwo', 
    'threethree', 
    'oneone', 
    'onetwo', 
    'onethree'], 
'loopone': ['oneone', 'onetwo', 'onethree'], 
'loopthree': ['threeone', 'threetwo', 'threethree'], 
'looptwo': ['twoone', 'twotwo', 'twothree']} 
2

就在列表理解使用兩個for條款。但是請注意,字典是沒有順序的,因此結果列表可以以不同的順序顯得比它們最初被放置在詞典:

>>> ListDict['loopfour'] = [x for y in ListDict.values() for x in y] 
>>> ListDict['loopfour'] 
['oneone', 'onetwo', 'onethree', 'twoone', 'twotwo', 'twothree', 'threeone', 'threetwo', 'threethree'] 

如果你想那麼它下令:

>>> ListDict['loopfour'] = [x for k in ['loopone', 'looptwo', 'loopthree'] for x in ListDict[k]] 
>>> ListDict['loopfour'] 
['oneone', 'onetwo', 'onethree', 'twoone', 'twotwo', 'twothree', 'threeone', 'threetwo', 'threethree'] 
+0

啊,這只是一個擴展。但這比我笨拙的解決方案簡單得多。但是,這裏假設python3.6在哪裏排序。 –

+0

@cᴏʟᴅsᴘᴇᴇᴅ因爲我沒有機會評論你的解決方案,所以不要使用'reduce(lambda x,y:x + y',這已經實現爲'sum'。但是問題在於「+」對於列表來說效率很低,不要把這樣的列表弄平,這是一種反模式,事實上,你有'鏈',所以你需要的只是'chain.from_iterable(d.values())' –

+0

@ juanpa.arrivillaga你不需要一個'*'或者'.from_iterable()'來工作嗎? – AChampion