[英]Check if value exists in the list
假设我有123-0-1
,我想检查列表中是否存在该值。 以下是我的列表:
df = [
{'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
{'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
]
在SQL中,我将使用:
select mpls, source from df where source = 192.168.10.10
从列表中,我想从源192.168.10.10
提取mpls 123-0-1
,以便可以获取正确的目标12.168.100.10
。
df
不是数据框。 这是词典列表。
因此,您唯一的选择是循环和if
条件:
for connection in df:
if connection['source'] == '192.168.10.10':
print(connection['mpls'])
print(connection['destination'])
# do whatever with connection. Can also break if it is guaranteed to be unique.
但是,如果df
是数据帧,则可以使用pandas索引语法:
relevant_rows = df[df['source'] == '192.168.10.10']
relevant_rows
那么将是一个新的数据帧,其行是那些source
等于'192.168.10.10'
。
import pandas as pd
data = [
{'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
{'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
]
df = pd.DataFrame(data)
print(df)
# destination mpls source
# 0 12.168.100.10 123-0-1 192.168.10.10
# 1 10.12.129.200 123-0-1 192.168.10.15
relevant_rows = df[df['source'] == '192.168.10.10']
print(relevant_rows)
# destination mpls source
# 0 12.168.100.10 123-0-1 192.168.10.10
为什么不建立一个数据框呢?
df = pd.DataFrame(df)
df[df['source'] == '192.168.10.10']
在使用列表时,这是使用列表理解的一种可能的解决方案:
[(x['mpls'], x['destination']) for x in df if x['source'] == '192.168.10.10']
它基于source
返回带有mpls
和destination
的元组:
[('123-0-1', '12.168.100.10')]
其他答案很好。 只是想展示next
也可以被使用:
df = [{'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'}, {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}]
try:
target = next(x for x in df if x['source'] == '192.168.10.10')
except StopIteration:
print('Value not found!')
else:
print(target['mpls']) # -> 123-0-1
print(target['destination']) # -> 12.168.100.10
请注意,这仅返回符合条件的第一个 dictionary
。 根据您的SQL
语句,看来您想全部获取它们。
我们还可以使用filter
功能从列表中获取过滤数据。 filtered_list = filter((lambda x: x['source'] == '192.168.10.10'), df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.