简明的Python 3.x批量字典查找
发布时间:2020-12-20 12:35:31 所属栏目:Python 来源:网络整理
导读:我有大量的字符串,我想转换为整数.在 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 re
我有大量的字符串,我想转换为整数.在
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','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循环.这对大型列表来说是最佳的吗? 解决方法
dict的键必须是可清除的,其中列表(例如x)不是,这就是为什么当你尝试使用x作为键来索引dict时你得到TypeError:unhashable类型:’list’错误的原因d.
如果您尝试执行批量字典查找,则可以使用operator.itemgetter方法: from operator import itemgetter itemgetter(*x)(d) 返回: (1,3) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |