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

3

我已经编写了代码,它可以将我的计算机中的文件创建键值对,并将它们存储在列表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'。但我需要的键名是A, B, G, F, M, N, S, X, Y, Z。因此,对于那些不在输出中的键,输出应该显示类似于"A不在列表中""B不在列表中"


展示一下你尝试过的内容。 - user1907906
如果你想匹配逗号,[a,b,g,f,m,n,s,x,y,z]+ 等同于 [,abgfmnsxyz]+,如果你不想匹配逗号,应该使用 [abgfmnsxyz]+ - perreal
我不想要逗号。我希望输出为“A不在列表中”,如果其他字母也不在列表中,也是同样的情况...我对此没有任何想法... - Ruchir
4个回答

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

你为什么每次都要创建一个新的字典? - Ashwini Chaudhary

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接