如何在Python中从键值对中搜索键

3 投票
4 回答
5454 浏览
提问于 2025-04-18 02:28

我写了一段代码,这段代码从我电脑上的一个文件中创建了键值对,并把它们存储在一个叫 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

现在我想检查某个特定的键是否在这个列表里。比如,我的代码生成了这样的输出:

[('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')]

在输出中,键是 'X''Y''Z''N'。但是我想找的键是 ABGFMNSXYZ。对于那些不在输出中的键,输出应该显示类似 "A not in list""B not in list" 这样的内容。

4 个回答

1
if ('X', '-6.511') in mylist:
   print('Yes')
else:
   print('No')

用列表(List)或者Numpy数组来创建我的列表(mylist)。

1
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
3
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)

在你遍历列表的时候,使用一个变量和一个打印函数。

我觉得这就是你想要的。

2

你可以把你的元组列表当作字典来读取,并检查某个键是否存在:

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

撰写回答