我有很多想转换为整数的字符串。在Python 3.7中执行列表的字典查找的最简洁方法是什么?
例如:
d = {'frog':1, 'dog':2, 'mouse':3}
x = ['frog', 'frog', 'mouse']
result1 = d[x[0]]
result2 = d[x]
result
等于1
,但不可能使用result2
:
TypeError Traceback (most recent call last)
<ipython-input-124-b49b78bd4841> in <module>
2 x = ['frog', 'frog', 'mouse']
3 result1 = d[x[0]]
----> 4 result2 = d[x]
TypeError: unhashable type: 'list'
一种方法是:
result2 = []
for s in x:
result2.append(d[s])
其结果为[1, 1, 3]
,但需要一个for循环。大型列表是否最合适?
答案 0 :(得分:9)
字典的键必须是可哈希的,列表(例如x
)不能哈希,这就是为什么在尝试使用{{1}时收到TypeError: unhashable type: 'list'
错误的原因}作为索引字典x
的键。
如果您要执行批量字典查找,则可以使用d
方法:
operator.itemgetter
这将返回:
from operator import itemgetter
itemgetter(*x)(d)
答案 1 :(得分:4)
如果您使用默认的python,则可以进行列表理解:
result = [d[i] for i in x]
如果您愿意使用numpy
解决方案,则可以使用条件替换。对于大型输入,这可能是最快的:
import numpy as np
result = np.array(x)
for k, v in d.items(): result[result==k] = v
最后pandas
有一个.replace
import pandas as pd
result = pd.Series(x).replace(d)