[英]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.