[英]Compare values in a list of dictionaries and return only dictionaries with highest values
[英]Return a list of values of dictionaries inside a list
我有一個包含字典的列表,每個字典都有相同的鍵和不同的值,
如何獲得列表中每個字典的值的列表?
使用dictionary.values()
我可以獲得字典值的列表,但是如果它在數組中怎么辦?
是否有必要進行for循環以獲取列表中的每個字典?
這就是我要的:
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
您可以對兩個任務使用列表推導:
>>> 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
實例。
或者您可以使用lambda
:
>> b = map(lambda x: x.values(), a)
>> reduce(lambda x, y: x+ y, b)
>> [0, 2, 1, 3, 5, 4, 6, 3, 2]
>> map(lambda x: x['a'], a)
>> [0, 3, 6]
您使用一個for
循環:
all_values = []
for d in array:
all_values.extend(d.values())
values_of_a = []
for d in array:
values_of_a.append(d["a"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.