python - 如何从python中的键值对中搜索键

标签 python arrays list dictionary

我编写了从我的计算机创建文件的键值对并将它们存储在列表 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' 但我要查找的键是 ABGFM, N, S, X, Y, Z >。因此对于那些不在输出中的键,输出应该显示类似“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)

在遍历列表时使用变量和打印函数

我想这就是你想要的。

关于python - 如何从python中的键值对中搜索键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23028414/

相关文章:

python - ElasticSearch地理距离查询

c# - 项目属性清除后添加的项目值发生变化

Java数组向第一个添加新值并删除最后一个

c - 从 C 中的数组中删除元素

java - 如何设置ImageResource列表<Item>

java - 反转列表中元素的顺序

python - 在OpenCV中设置相机分辨率-预先构建与自定义构建

python - django-braces 访问 mxin 每个 mixin 不同的 login_url 重定向

python - 将 Tensorflow Keras 模型移植到 Tensorflow 版本 1.14.0 时出错

java - 2D JButton 数组,想要为游戏添加 Action 监听器