Python:仅保留匹配的项目,并将其余项目留在列表

时间:2017-05-19 10:38:43

标签: python-2.7

  

[{“timestamp”:1495126913.0,“client_ip”:“10.200.3.55”,   “remote_host”:“78.47.139.58”},{“timestamp”:1495126913.0,   “client_ip”:“10.200.3.55”,“remote_host”:“201.83.41.11”},   {“timestamp”:1495126913.0,“client_ip”:“10.200.3.55”,“remote_host”:   “175.106.59.78”},{“timestamp”:1495126915.0,“client_ip”:   “10.200.3.55”,“remote_host”:“175.106.59.78”},{“timestamp”:   1495126915.0,“client_ip”:“10.200.3.55”,“remote_host”:“175.106.59.78”},{“timestamp”:1495126915.0,“client_ip”:   “10.200.3.55”,“remote_host”:“78.47.139.58”},{“timestamp”:   1495126915.0,“client_ip”:“10.200.3.55”,“remote_host”:“201.83.41.11”},{“timestamp”:1495126917.0,“client_ip”:   “10.200.3.55”,“remote_host”:“175.106.59.78”},{“timestamp”:   1495126917.0,“client_ip”:“10.200.3.55”,“remote_host”:“201.83.41.11”},{“timestamp”:1495126917.0,“client_ip”:   “10.200.3.55”,“remote_host”:“201.83.41.11”}]

在Python中,查找与remote_host = 78.47.139.58匹配的所有条目。显示所有但仅匹配的一个并保存到列表中。 例如:

预期答案

  

[{“timestamp”:1495126913.0,“client_ip”:“10.200.3.55”,   “remote_host”:“78.47.139.58”},{“timestamp”:1495126915.0,   “client_ip”:“10.200.3.55”,“remote_host”:“78.47.139.58”}]

1 个答案:

答案 0 :(得分:0)

你可以通过

来完成
list_arr= [{"timestamp": 1495126913.0, "client_ip": "10.200.3.55", "remote_host": "78.47.139.58"}, {"timestamp": 1495126913.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"}, {"timestamp": 1495126913.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"}, {"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"}, {"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"}, {"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "78.47.139.58"}, {"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"}, {"timestamp": 1495126917.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"}, {"timestamp": 1495126917.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"}, {"timestamp": 1495126917.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"}]
filtered = [_ for _ in list_arr if _['remote_host'] == '78.47.139.58']
print(filtered)

<强>已更新

另一种方法是使用lambda方法

filt = list(filter(lambda x: x['remote_host'] == '78.47.139.58', list_arr))
print(filt)

示例演示链接https://repl.it/HSRf/4