Python dict值为整数列表

时间:2014-11-25 13:36:57

标签: python json list dictionary

我对Python很新。我有一个词典列表。

[{"x": "23"}, {"x": "14"}, {"x": "9"}, {"x": "19"}, {"x": "21"}, {"x": "14"}, {"x": "16"}, {"x": "11"}, {"x": "9"}, {"x": "6"}, {"x": "24"}, {"x": "13"}]

我想提取与x键关联的值并绘制它们。要做到这一点,列表必须如下所示,值必须是整数(或浮点数)。

[23, 14, 9, 19, 21, 14, 16, 11, 9, 6, 24, 13]

我的问题是:我如何

  1. 提取这些值,
  2. 将它们转换为整数?

3 个答案:

答案 0 :(得分:1)

这可以使用字典的get方法使用列表理解来完成。

>>> l = [{"x": "23"}, {"x": "14"}, {"x": "9"}, {"x": "19"}, {"x": "21"}, {"x": "14"}, {"x": "16"}, {"x": "11"}, {"x": "9"}, {"x": "6"}, {"x": "24"}, {"x": "13"}]
>>> [i.get('x') for i in l]
['23', '14', '9', '19', '21', '14', '16', '11', '9', '6', '24', '13']

如果你喜欢它们作为整数,请在列表理解

中转换它们
>>> [int(i.get('x')) for i in l]
[23, 14, 9, 19, 21, 14, 16, 11, 9, 6, 24, 13]

答案 1 :(得分:1)

使用list comprehension。对于每个项目,获取"x"并转换为int

[int(item['x']) for item in mylist]

如果您需要花车,请将int更改为float

答案 2 :(得分:1)

您可以使用list comprehension

>>> mylist = [{'x': '23'}, {'x': '14'}, {'x': '9'}, {'x': '19'}, {'x': '21'}, {'x': '14'}, {'x': '16'}, {'x': '11'}, {'x': '9'}, {'x': '6'}, {'x': '24'}, {'x': '13'}]
>>> [ int(item.values()[0]) for item in mylist]
[23, 14, 9, 19, 21, 14, 16, 11, 9, 6, 24, 13]

map

>>> map(lambda x: int(x['x']), mylist)
[23, 14, 9, 19, 21, 14, 16, 11, 9, 6, 24, 13]