gpt4 book ai didi

python - 比较字典python中的值

转载 作者:太空宇宙 更新时间:2023-11-03 13:03:00 26 4
gpt4 key购买 nike

我在 Python 中有 2 个具有这种格式的嵌套字典:

1166869: {'probL2': '0.000', 'probL1': '0.000', 'pronNDiff_site': '1.000', 'StateBin': '0', 'chr': 'chrX', 'rangehist': '59254000-59255000', 'start_bin': '59254000', 'countL2': '4', 'countL1': '0'} 

1166870: {'probL2': '0.148', 'probL1': '0.000', 'pronNDiff_site': '0.851', 'StateBin': '0', 'chr': 'chr2', 'rangehist': '59254000-59255000', 'start_bin': '59255000', 'countL2': '5', 'countL1': '15'}

1166871: {'probL2': '0.000', 'probL1': '0.000', 'pronNDiff_site': '1.000', 'StateBin': '0', 'chr': 'chrY', 'rangehist': '59290000-59291000', 'start_bin': '59290000', 'countL2': '1', 'countL1': '2'}

其中 1166869、1166870 和 1166871 代表我从中读取数据的文件中的一行,其余键是数据本身。

现在我想制作一个列表,将所有不同的值存储在键“chr”中,因为有一些重复的值。

我怎样才能通过字典并比较这两个值?此代码无效:

for k in range(len(file_dict)):
for j in range(len(file_dict)-1):
if (file_dict[j]["chr"] != file_dict[k]["chr"]):
list_chr.append(file_dict[j]["chr"])

最佳答案

使用一组,一次性使用所有项目:

chr = { v['chr'] for v in file_dict.itervalues() }

这使用集合理解在一行代码中生成您的集合。

集合推导是在 Python 2.7 中引入的;在早期版本中使用:

chr = set(v['chr'] for v in file_dict.itervalues())

在 Python 3 中,您需要将 .itervalues() 替换为 .values()

您自己的代码不起作用,因为 python 字典不是列表;您不是按索引检索值,而是按键检索值。您必须将其更改为:

for key in file_dict:
for other_key in file_dict:
if key == other_key:
continue

if file_dict[key]['chr'] != file_dict[otherkey]['chr']:
list_chr.append(filed_dict[key]['chr'])

但这确实效率低下,更不用说不正确了。

关于python - 比较字典python中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13761994/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com