【问题标题】:Python, Combining lists within a dictPython,在字典中组合列表
【发布时间】:2018-01-11 11:03:45
【问题描述】:

是否可以将 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'] 调用并返回组合列表

【问题讨论】:

  • ListDict['loopfour'] = [el for l in ListDict.values() for el in l].
  • 列表是可变的。您想如何处理列表中的值发生变化的情况?

标签: python list dictionary append add


【解决方案1】:

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

【讨论】:

  • 啊,这只是一个扩展。但这比我笨拙的解决方案要简单得多。但是,这假设字典是在 python3.6 中排序的。
  • @cᴏʟᴅsᴘᴇᴇᴅ 因为我没有机会评论您的解决方案,所以不要使用reduce(lambda x, y: x + y,这已经实现为sum。但问题在于+ 对列表效率低下。不要像这样扁平化列表,这是一种反模式。确实,您已经拥有chain,所以您只需要chain.from_iterable(d.values())
  • @juanpa.arrivillaga 你不需要*.from_iterable() 才能工作吗?
  • @juanpa.arrivillaga 谢谢。它适用于 AChampion 的 * 修改。我已经为后代取消删除它,但我认为这也是一个很好的解决方案。
  • @cᴏʟᴅsᴘᴇᴇᴅ 次要的点,应该是chain.from_iterable(d.values()),至少,它会比chain(*d.values()) 效率高一点,因为它避免了参数解包,但这并不是真正的除非有大量争论,否则很重要。
猜你喜欢
  • 2010-12-02
  • 2013-02-19
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 2020-03-03
  • 1970-01-01
相关资源
最近更新 更多