我有一個看起來像這樣的串列:
[{'ip': 'x.x.x.x',
'error': True,
'reason': 'Reserved IP Address',
'reserved': True,
'version': 'IPv4'},
{'ip': 'x.x.x.x',
'error': True,
'reason': 'Reserved IP Address',
'reserved': True,
'version': 'IPv4'},
{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Munich',
'region': 'Bavaria',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'},
{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Düsseldorf',
'region': 'North Rhine-Westphalia',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'}]
我需要的是一種洗掉這些元素的方法,而不是在里面有一個“錯誤”或“原因:'保留 IP 地址'”元素,并且只獲取具有完整資料的元素。像這樣:
#Removing unnecesary elements
[{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Munich',
'region': 'Bavaria',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'},
{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Düsseldorf',
'region': 'North Rhine-Westphalia',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'}]
有沒有辦法做到這一點?
uj5u.com熱心網友回復:
嘗試使用串列理解:
>>> [d for d in mylist if not d.get("error") and d.get("reason")!="Reserved IP Address"]
uj5u.com熱心網友回復:
使用過濾器方法的另一種可能方法,對于更復雜的條件可能更靈活
list_of_dict = [{'ip': 'x.x.x.x',
'error': True,
'reason': 'Reserved IP Address',
'reserved': True,
'version': 'IPv4'},
{'ip': 'x.x.x.x',
'error': True,
'reason': 'Reserved IP Address',
'reserved': True,
'version': 'IPv4'},
{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Munich',
'region': 'Bavaria',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'},
{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Düsseldorf',
'region': 'North Rhine-Westphalia',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'}]
def contains_error(dictionary):
return False if ('error' or 'reason') in dictionary.keys() else True
result = list(filter(contains_error, list_of_dict))
print(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/425611.html
上一篇:我需要從串列中搜索字串以查找模式
下一篇:將int值添加到多陣列int串列
