Python,在di中组合列表

2024-04-26 23:46:46 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以将dict中的列表合并到一个新键? 例如,我有一个dict设置

    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['four']调用并返回组合列表


Tags: 列表dict新键twothreelistdictonetwolooponeonethree
1条回答
网友
1楼 · 发布于 2024-04-26 23:46:46

只需在列表理解中使用两个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']

相关问题 更多 >