2017-08-03 106 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