【问题标题】:Find all indices of a value in a dictionary python在字典python中查找值的所有索引
【发布时间】:2016-06-11 01:09:15
【问题描述】:

我有一个从 netCDF 文件中的变量创建的字典。我还按时间顺序对所有这些变量进行了排序。某些键有重复的值。我想在一个键中找到特定值的所有索引,并从另一个键中检索相应的索引:

例如:

test_dict = {}
test_dict['time'] = [1,2,3,4]
test_dict['number'] = [12,14,12,13]
test_dict['number2'] = [20,21,22,23]

在 test_dict 中,我想在键“number”中找到所有出现的 12 的索引,并在“number2”中获取相应的值。所以结果应该是:

idx = [0,2]
nums_interest = [test_dict['number2'][i] for i in idx]
>>>> [20,22]

我尝试使用以下方法查找“数字”中唯一值的数量:

num_unique = np.unique(test_dict['number'])
>>>> [12,13,14]

然后我想找到这些唯一事件的所有索引。

 idx2 = [test_dict['number'].index(num_unique[0])
 >>> 0

我有两个主要问题: 1. 我可以找到第一个索引,但不能找到重复索引。 2. 我想遍历唯一数字列表并获取每个唯一值的索引,而不仅仅是 num_unique[0] 问题:在字典中查找某个值的索引并在不同键中提取相同索引的值的最佳方法是什么?

【问题讨论】:

  • 你不能用[j for i,j in zip(test_dict['number'],test_dict['number2']) if i==12]吗?您不必那样找到12 的索引
  • @GughanRavikumar 成功了!
  • 很高兴为您提供帮助。我已将其添加为答案。如果您觉得它有用,请将其标记为已接受,以便阅读此问题的其他人可以从中受益

标签: python dictionary


【解决方案1】:

根据字典中另一个键的索引从一个键返回值

test_dict = {}
test_dict['number'] = [12,14,12,13]
test_dict['number2'] = [20,21,22,23]
print([j for i,j in zip(test_dict['number'],test_dict['number2']) if i==12])

返回[20,22]

获取列表中某个值的所有出现的索引

indices = [i for i,j in enumerate(dict['number']) if j==12]

给出indices 等于[0,2]

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多