【问题标题】:How do I remove a list item from a dict value?如何从 dict 值中删除列表项?
【发布时间】:2018-01-23 05:51:44
【问题描述】:

我有一个包含主机名键和列表值的主机字典。我希望能够从每个值的列表中删除任何 fruit_ 项目。

host = { 
  'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'], 
  '123.com': None, 
  'foo.com': ['fruit_tomatoes', 'veg_potatoes']
}

for v in host.values():
  if v is not None:
    for x in v:
      try:
        # creating my filter
        if x.startswith('fruit_'):
        # if x finds my search, get, or remove from list value
         host(or host.value()?).get/remove(x)# this is where i'm stuck
        print(hr.values(#call position here?)) # prove it
      except:
        pass

我被困在评论区,我觉得我错过了另一个迭代(某个地方的新列表?),或者我不明白如何写回列表值。任何方向都会有所帮助。

【问题讨论】:

  • 在您的示例中,if v is not None: 将始终为 True。你可能已经知道了
  • 是的,没关系。我猜你在host 的值中有一个None 没有发布?我只是想确保您认为它不会捕获 [None]
  • 我想我应该更新一下,''123.com': [ None ], ' 应该是 '123.com': None,不在列表中。
  • 没问题,我不是故意挑剔的,我猜你已经知道了!

标签: python python-3.x list dictionary


【解决方案1】:

从列表中过滤项目的更好方法是使用带有过滤条件的列表推导并创建一个新列表,如下所示。

host = {
    'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'],
    '123.com': [None],
    '456.com': None,
    'foo.com': ['fruit_tomatoes', 'veg_potatoes']
}


def reconstruct_list(vs):
    return vs if vs is None else [
        v for v in vs if v is None or not v.startswith('fruit_')
    ]


print({k: reconstruct_list(vs) for k, vs in host.items()})

输出

{'abc.com': ['veg_carrots'], '123.com': [None], '456.com': None, 'foo.com': ['veg_potatoes']}

在这种特殊情况下,列表的各个值被过滤,并使用字典理解创建一个新的字典对象。

【讨论】:

  • @hobbes 我认为您的数据在某些情况下将None 作为值而不是[None]。对吗?
  • 没错,我已经在上面进行了更新。它不应该在列表中。
  • @hobbes 我更新了答案以适应 None 两种情况。它只是从过滤中忽略了None
  • 哇,成功了,谢谢!我需要一些时间来消化那个列表理解,我理解了一点,但仍然抓住了把它分解成块,按照操作顺序。
  • @hobbes 以this开头。
【解决方案2】:

用字典理解重建字典怎么样:

>>> host = { 
  'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'], 
  '123.com': [None] , 
  'foo.com': ['fruit_tomatoes', 'veg_potatoes']
}

>>> {k: [x for x in v if not str(x).startswith('fruit_') or not x] for k, v in host.items()}
{'abc.com': ['veg_carrots'], '123.com': [None], 'foo.com': ['veg_potatoes']}

或者如果'123.com' 仅具有None 作为值,您可以这样做:

>>> host = { 
  'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'], 
  '123.com': None , 
  'foo.com': ['fruit_tomatoes', 'veg_potatoes']
}

>>> {k: v if not v else [x for x in v if not x.startswith('fruit_')] for k, v in host.items()}
{'abc.com': ['veg_carrots'], '123.com': None, 'foo.com': ['veg_potatoes']}

【讨论】:

  • 也正确,谢谢。在分解您的示例以及上面发布的示例时,这很好比较。
【解决方案3】:

你可以试试这样的:

host = {
  'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'],
  '123.com': None,
  'foo.com': ['fruit_tomatoes', 'veg_potatoes']
}


print({i:[k for k in j if not k.startswith('fruit_')] if j!=None  else None for i,j in host.items() })

但是如果没有 None 那么你可以试试这个有趣的方法:

print(dict(map(lambda z,y:(z,list(filter(lambda x:not x.startswith('fruit_'),host[y]))),host,host)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    相关资源
    最近更新 更多