[英]Convert List into Dictionary and Convert its values and keys to integer with List Comprehension
suppose we have a list of list called A
: 假设我们有一个名为
A
的列表的列表:
A = [['1', '200'], ['2', '450'], ['3', '300']]
What I want to do are convert list of lists above into a dictionary with first element as key and second as value, and after that I want to make both of keys and values converted to integer. 我想要做的是将上述列表的列表转换成字典,其中第一个元素为键,第二个为值,然后我想将键和值都转换为整数。
So it will be as follows: 因此将如下所示:
A = {1: 200,
2: 450,
3: 300}
With all keys and values are integer. 与所有键和值是整数。
I tried list comprehension for this: 我为此尝试了列表理解:
A = dict(zip(int(a), int(b)) for a, b in row for row in A)
Got error on it: 出现错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'row' is not defined
You don't need zip()
here, just drop that, and you can loop directly over A
and unpack into a
and b
: 您无需在这里使用
zip()
,只需将其删除,就可以直接在A
循环并解压缩为a
和b
:
A = dict((int(a), int(b)) for a, b in A)
That's a generator expression passing tuples to the dict()
callable. 那是一个生成器表达式,将元组传递给可调用的
dict()
。
If you can, you want to use a dictionary comprehension instead; 如果可以的话,您应该改用字典理解; that's available in Python 2.7 and newer (including all Python 3.x releases):
在Python 2.7和更高版本(包括所有Python 3.x版本)中可用:
A = {int(a): int(b) for a, b in A}
Demo: 演示:
>>> A = [['1', '200'], ['2', '450'], ['3', '300']]
>>> dict((int(a), int(b)) for a, b in A)
{1: 200, 2: 450, 3: 300}
>>> {int(a): int(b) for a, b in A}
{1: 200, 2: 450, 3: 300}
A = [['1', '200'],['2', '450'],['3','300']]
B_dict = {int(i[0]): int(i[1]) for i in A}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.