我有一个从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]我试图使用以下方法找到'number'中唯一值的数量:
num_unique = np.unique(test_dict['number']) >>>> [12,13,14]然后我想找到这些独特事件的所有索引。
idx2 = [test_dict['number'].index(num_unique[0]) >>> 0我有两个主要问题:1。我可以找到第一个索引,但不能重复索引。 2.我想循环遍历唯一数字列表并获取每个唯一值的索引而不仅仅是num_unique [0]问题:在字典中查找某个值的索引并提取相同索引的值的最佳方法是什么用不同的钥匙?
I have a dictionary created from variables in a netCDF file. I have also sorted all of these variables in the order of time. There are repeated values for some of the keys. I want to find all of the indices for a specific value in one key and retrieve the corresponding indices from another key:
For example:
test_dict = {} test_dict['time'] = [1,2,3,4] test_dict['number'] = [12,14,12,13] test_dict['number2'] = [20,21,22,23]in test_dict I want to find the indices of all occurrences of 12 in the key 'number' and get the corresponding values in 'number2'. So the result should be:
idx = [0,2] nums_interest = [test_dict['number2'][i] for i in idx] >>>> [20,22]I have tried to find the number of unique values in 'number' using:
num_unique = np.unique(test_dict['number']) >>>> [12,13,14]Then I want to find all indices of these unique occurrences.
idx2 = [test_dict['number'].index(num_unique[0]) >>> 0I have two main problems: 1. I can find the first index, but not repeating indices. 2. I want to loop through the list of unique numbers and get indices for every unique value not just num_unique[0] question: what is the best way to find indices for a certain value in a dictionary and extract the values for the same indices in a different key?
最满意答案
根据dict中另一个键的索引从一个键返回值
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]
To return values from one key based on index of another key in a dict
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])returns [20,22]
To get indices of all occurences of a value in a list
indices = [i for i,j in enumerate(dict['number']) if j==12]gives indices equals [0,2]
更多推荐
发布评论