【问题标题】:How to Insert Each Dictionary Value into a List After the Corresponding Key?如何将每个字典值插入到对应键之后的列表中?
【发布时间】:2020-09-09 21:13:55
【问题描述】:

我有一个元素列表,我想在关键元素之后将字典值插入到该列表中:

listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}

给出以下内容:

['a', 'b', 'x', 'c', 'd', 'y']

Pythonic 的方法是什么?

【问题讨论】:

  • “平面地图”列表理解。请参阅coderwall.com/p/rcmaea/… - 它显示了带有迭代和 result_list.add 的“正常”方法以及使用列表理解的方法。两种方法都在这里起作用。两者都是“Pythonic”。
  • 也就是说,考虑['a', 'b', 'c' ..] -> [['a'], ['b','x'], ['c'] ..] 的普通“地图”。它的“平面图”将所有映射的序列连接在一起。使用两个离散的列表推导式可能是开始和查看操作相互支持的有用方式。

标签: python list dictionary list-comprehension data-manipulation


【解决方案1】:

这是一个理解:

>>> listicle = ['a', 'b', 'c', 'd']
>>> some_new_elements = {'b':'x', 'd':'y'}
>>> sentinel=object()
>>> [x for t in ((e, some_new_elements.get(e, sentinel)) for e in listicle) for x in t if x !=sentinel]
['a', 'b', 'x', 'c', 'd', 'y']

【讨论】:

    【解决方案2】:

    尝试使用类似于flatmapitertools.chain.from_iterable

    from itertools import chain
    listicle = ['a', 'b', 'c', 'd']
    some_new_elements = {'b':'x', 'd':'y'}
    output = list(chain.from_iterable([[x, some_new_elements[x]] if x in some_new_elements else [x] for x in listicle]))
    print(output) # output:  ['a', 'b', 'x', 'c', 'd', 'y']
    

    【讨论】:

      【解决方案3】:

      正确方法:

      import itertools
      
      listicle = ['a', 'b', 'c', 'd']
      some_new_elements = {'b':'x', 'd':'y'}
      
      new_map = ([m, some_new_elements[m]] if m in some_new_elements else [m] for m in listicle)
      print(list(itertools.chain.from_iterable(new_map)))
      >>> ['a', 'b', 'x', 'c', 'd', 'y']
      

      无需列表理解的简单方法:

      listicle = ['a', 'b', 'c', 'd']
      some_new_elements = {'b':'x', 'd':'y'}
      
      output = []
      for x in listicle:
          output.append(x)
          if(x in some_new_elements):
              output.append(some_new_elements[x])
      
      print(output)
      >>>['a', 'b', 'x', 'c', 'd', 'y']
      

      【讨论】:

      • @user2864740 谢谢,我添加了更多上下文,但我还没有找到完美的答案。
      • 可以用([m,some_new_elements[m]] if m in some_new_elements else [m] for m in listicle)生成简单地图。这会产生一系列元素,如['a'](不匹配)和['b','x'](匹配)。这个结果可以组合成一个“平面地图”或使用类似itertools.chain/chain_from_iterable(这可能更清楚)将所有包含的列表扁平化为一个列表。
      • 我发现没有列表理解的解决方案更具可读性。 +1
      • 两种方式都是“正确的”。将两者都包含在答案中会使它变得更强大。干得好!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多