[英]How do I remove a list item from a dict value?
我有一個包含主機名鍵和列表值的主機字典。 我希望能夠從每個值的列表中刪除任何水果_項目。
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
我被評論區困住了,我覺得我錯過了另一個迭代(某處的新列表?),或者我不明白如何寫回列表值。 任何方向都會有所幫助。
從列表中過濾項目的更好方法是使用帶有過濾條件的列表理解並創建一個新列表,如下所示。
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']}
在這種特殊情況下,列表的各個值被過濾,並使用字典理解創建一個新的字典對象。
用字典理解重建字典怎么樣:
>>> 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']}
你可以嘗試這樣的事情:
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)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.