Ste*_*eve 3 python dictionary python-3.x
我有大量的字符串,我想转换为整数.在Python 3.7中执行列表字典查找的最简洁方法是什么?
例如:
d = {'frog':1, 'dog':2, 'mouse':3}
x = ['frog', 'frog', 'mouse']
result1 = d[x[0]]
result2 = d[x]
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)
一种方法是:
result2 = []
for s in x:
result2.append(d[s])
Run Code Online (Sandbox Code Playgroud)
这导致[1, 1, 3]但需要一个for循环.这对大型列表来说是最佳的吗?
dict的键必须是可清除的,列表(例如x,不是),这就是为什么TypeError: unhashable type: 'list'当你尝试x用作索引dict的键时你得到错误的原因d.
如果您尝试执行批量字典查找,则可以使用该operator.itemgetter方法:
from operator import itemgetter
itemgetter(*x)(d)
Run Code Online (Sandbox Code Playgroud)
返回:
(1, 1, 3)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |