【问题标题】:How to eliminate second item of a nested dictionary and skip the empty nested lists?如何消除嵌套字典的第二项并跳过空的嵌套列表?
【发布时间】:2021-01-30 03:05:18
【问题描述】:

我在删除嵌套在字典列表中的列表的第二项时遇到问题。我认为可能是因为有几个空列表,所以索引不起作用。 如何删除每个嵌套列表对的第二项,同时跳过空列表?

最后,嵌套列表应该被展平,因为它不再有第二对了。

列表如下所示:

list_dict = [{"name": "Ken", "bla": [["abc", "ABC"],["def", "DEF"]]}, 
             {"name": "Bob", "bla": []}, #skip the empty list
             {"name": "Cher", "bla":[["abc", "ABC"]]}]

期望的输出:

wanted = [{"name": "Ken", "bla": ["abc", "def"]}, 
             {"name": "Bob", "bla": []}, 
             {"name": "Cher", "bla":["abc"]}]

我的代码:

for d in list_dict:
    for l in list(d["bla"]):
        if l is None:
            continue  #use continue to ignore the empty lists
        d["bla"].remove(l[1]) #remove second item of every nested list pair (gives error).





【问题讨论】:

  • 最后一行缩进太多。
  • 顺便说一句,我猜if l is None: 永远不会是真的,因为它总是list 而不是None

标签: python list loops dictionary nested


【解决方案1】:

您可以使用[:1] 仅获取列表中的第一项(也适用于零长度列表):

list_dict = [{"name": "Ken", "bla": [["abc", "ABC"],["def", "DEF"]]}, 
             {"name": "Bob", "bla": []}, #skip the empty list
             {"name": "Cher", "bla":[["abc", "ABC"]]}]


for i in list_dict:
    i['bla'] = [ll for l in [l[:1] for l in i['bla']] for ll in l]

print(list_dict)

打印:

[{'name': 'Ken', 'bla': ['abc', 'def']}, 
 {'name': 'Bob', 'bla': []}, 
 {'name': 'Cher', 'bla': ['abc']}]

【讨论】:

    【解决方案2】:

    您可以使用itertools.chain.from_iterable 展平列表。

    例子:

    In [24]: l = [["abc", "ABC"],["def", "DEF"]]
    
    In [25]: list(itertools.chain.from_iterable(l))
    Out[25]: ['abc', 'ABC', 'def', 'DEF']
    

    扁平化列表后,您可以对其进行切片以获取每个第二个元素:

    In [26]: flattened = list(itertools.chain.from_iterable(l))
    
    In [27]: flattened[::2]
    Out[27]: ['abc', 'def']
    

    【讨论】:

      【解决方案3】:

      你可以像这个例子一样使用chain.from_iterable

      from itertools import chain
      from collections.abc import Iterable
      
      list_dict = [{'name': 'Ken', 'bla': [['abc', 'ABC'], ['def', 'DEF']]},
       {'name': 'Bob', 'bla': []},
       {'name': 'Cher', 'bla': [['abc', 'ABC']]}]
      
      out = []
      for k in list_dict: 
               tmp = {} 
               for key, value in k.items(): 
                   # Check if the value is iterable
                   if not isinstance(value, Iterable): 
                       tmp[key] = value 
                   else: 
                       val = list(chain.from_iterable(value))[:1] 
                       tmp[key] = val 
               out.append(tmp)
      
      print(out)
      
      [{'name': 'Ken', 'bla': ['ABC', 'def', 'DEF']},
       {'name': 'Bob', 'bla': []},
       {'name': 'Cher', 'bla': ['ABC']}]
      

      【讨论】:

        【解决方案4】:

        这应该可以工作,即使给定的l 是空的:

        for d in list_dict:
            d["bla"][:] = (v[0] for v in d["bla"])
        

        为了提高效率,您可以在每个条目中提取一次d["bla"]

        for d in list_dict:
            l = d["bla"]
            l[:] = (v[0] for v in l)
        

        这会将list_dict 更改为:

        [{'name': 'Ken', 'bla': ['abc', 'def']},
         {'name': 'Bob', 'bla': []},
         {'name': 'Cher', 'bla': ['abc']}]
        
        

        请注意,此解决方案不会创建任何新列表。它只是修改现有列表。此解决方案比任何其他已发布的解决方案都更简洁、更高效。

        【讨论】:

          【解决方案5】:

          给定:

          list_dict = [{"name": "Ken", "bla": [["abc", "ABC"],["def", "DEF"]]}, 
                       {"name": "Bob", "bla": []}, #skip the empty list
                       {"name": "Cher", "bla":[["abc", "ABC"]]}]
          
          desired_dict = [{"name": "Ken", "bla": ["abc", "def"]}, 
                       {"name": "Bob", "bla": []}, 
                       {"name": "Cher", "bla":["abc"]}]
          

          您可以简单地重新创建 d['bra'] 成为您想要的。空列表将被跳过,因为没有可迭代的内容并且现有条目未更改:

          for d in list_dict:
              d['bla']=[sl[0] for sl in d['bla']]
          
          >>> list_dict==desired_dict
          True
          

          【讨论】:

            猜你喜欢
            • 2021-02-27
            • 2023-03-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-13
            • 2018-03-25
            相关资源
            最近更新 更多