返回列表中字典值的列表 [英] Return a list of values of dictionaries inside a list

查看:1256
本文介绍了返回列表中字典值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字典的列表,每个字典都有相同的键和不同的值,

I have a list that contains dictionaries, each of them have the same keys and different values,

如何获取列表中每个字典的值列表?

How can I get a list of values of every dictionary in the list?

使用dictionary.values()我可以获得字典值的列表,但是如果它在数组中怎么办?

With dictionary.values() I can get a list of values of a dictionary but what if it is inside an array?

是否有必要进行for循环以获取列表中的每本词典?

Is it necessary to do a for-loop to get every dictionary in the list?

这就是我想要的:

list= [{'a':0,'b':1,'c':2}, {'a':3,'b':4,'c':5}, {'a':6,'b':2,'c':3},]

all_values = [0,1,2,3,4,5,6] # THIS IS THE ACTUAL QUESTION

values_of_a = [0,3,6]  # THIS COULD BE BETTER IF POSSIBLE

推荐答案

您可以使用

You can use list comprehensions for both tasks:

>>> array = [{'a':0,'b':1,'c':2}, {'a':3,'b':4,'c':5}, {'a':6,'b':2,'c':3},]
>>> [y for x in array for y in x.values()]
[0, 1, 2, 3, 4, 5, 6, 2, 3]
>>> [x['a'] for x in array]  # Assuming that all dicts have an 'a' key
[0, 3, 6]
>>>

此外,array从技术上讲不是数组.这是一个列表. Python中的数组是 array.array 的实例.

Also, array is not technically an array. It is a list. Arrays in Python are instances of array.array.

这篇关于返回列表中字典值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆