获取基于python的字典中的值(其中键可能是重复的)的键

时间:2015-03-10 16:57:48

标签: python numpy itertools

我是python的新手。我有以下任务来迭代字典的所有值对以计算值(两个序列的汉明距离(每个值对是序列对))。然后,如果计算的汉明距离为1,我需要打印出相应的键。代码如下。

import numpy as np
import itertools
from scipy.spatial.distance import hamming

graph=[]
i=5
t1=tuple('aaaaa')
t2=tuple('aaaab')
t3=tuple('aaaac')
t4=tuple('aaaad')
t5=tuple('aaaaa')

population={'1':t1, '2':t2, '3':t3, '4':t4, '5':t5}

for pair in itertools.combinations(np.array(population.values()),2):
    if hamming(pair[0],pair[1])*i==1: graph.append(str(population.keys()[population.values().index(pair[0])]) +'\t' + str(population.keys()[population.values().index(pair[1])]) +'n')

print graph 

错误是:

Traceback (most recent call last):
  File "test.py", line 18, in <module>
    if hamming(pair[0],pair[1])*len==1: graph.append(str(population.keys()[population.values().index(pair[0])]) +'\t' + str(population.keys()[population.values().index(pair[1])]) +'n')
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

非常感谢任何评论。 编辑:我学会了从这个链接中的字典值访问密钥: Get key by value in dictionary 编辑:避免变量内置。

1 个答案:

答案 0 :(得分:0)

问题与不同类型的比较有关,可以用更简单的脚本来证明:

import numpy as np
mytuple = ('a', 'a')
myarray = np.array(mytuple)
[myarray].index(mytuple)

运行时,您会得到:

$ python hem.py

Traceback (most recent call last):
  File "hem.py", line 4, in <module>
    [myarray].index(mytuple)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

population.values()是一个元组列表,但pair [0]是一个np数组,因此它们永远不会正确比较。错误本身令人困惑,但您需要一种不同的方法来查找索引。