[英]How to search key from key-value pair in python
我編寫了從我的計算機創建文件的鍵值對並將它們存儲在列表a
中的代碼。 這是代碼:
groups = defaultdict(list)
with open(r'/home/path....file.txt') as f:
lines=f.readlines()
lines=''.join(lines)
lines=lines.split()
a=[]
for i in lines:
match=re.match(r"([a,b,g,f,m,n,s,x,y,z]+)([-+]?[0-9]*\.?[0-9]+)",i,re.I)
if match:
a.append(match.groups())
print a
現在我想查找特定鍵是否在該列表中。 例如,我的代碼生成這個 output:
[('X', '-6.511'),('Y', '-40.862'),
('X', '-89.926'),('N', '7304'),
('X', '-6.272'), ('Y', '-40.868'),
('X', '-89.979'),('N', '7305'),
('Y', '-42.101'),('Z', '238.517'),
('N', '7306'), ('Y','-43.334'),
('Z', '243.363'),('N', '7307')]
現在,在 output 中,鍵是'X'
, 'Y'
, 'Z'
, 'N'
但我要找的鍵是A
, B
, G
, F
, M
, N
, S
, X
, Y
, Z
. 因此,對於那些不在 output 中的鍵,output 應該顯示類似"A not in list"
, "B not in list"
內容。
for node in ['A', 'B', 'G', 'F', 'M', 'N', 'S', 'X', 'Y', 'Z']:
if node not in groups.keys():
print "%s not in list"%(node)
在遍歷列表時使用變量和打印功能
我想這就是你想要的。
您可以將您的元組列表讀取為dict並檢查密鑰是否存在:
d=[('X', '-6.511'),('Y', '-40.862'),
('X', '-89.926'),('N', '7304'),
('X', '-6.272'), ('Y', '-40.868'),
('X', '-89.979'),('N', '7305'),
('Y', '-42.101'),('Z', '238.517'),
('N', '7306'), ('Y','-43.334'),
('Z', '243.363'),('N', '7307')]
k=['A', 'B', 'G', 'F', 'M', 'N', 'S', 'X', 'Y', 'Z']
dt=dict(d)
for i in k:
if i in dt:
print i," has found"
else:
print i," has not found"
輸出:
A has not found
B has not found
G has not found
F has not found
M has not found
N has found
S has not found
X has found
Y has found
Z has found
mylist = [('X', '-6.511'),('Y', '-40.862'),
('X', '-89.926'),('N', '7304'),
('X', '-6.272'), ('Y', '-40.868'),
('X', '-89.979'),('N', '7305'),
('Y', '-42.101'),('Z', '238.517'),
('N', '7306'), ('Y','-43.334'),
('Z', '243.363'),('N', '7307')]
missing = [ x for x in 'ABGFMNSXYZ' if x not in set(v[0] for v in mylist) ]
for m in missing:
print "{} not in list".format(m)
得到:
A not in list
B not in list
G not in list
F not in list
M not in list
S not in list
if ('X', '-6.511') in mylist:
print('Yes')
else:
print('No')
對 mylist 使用 List 或 Numpy 數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.