python过滤器列表中的不同字典键值

时间:2015-12-24 16:14:19

标签: python

我有一个列表:

lis = [{"class":"math","teacher":"Joe"}, {"class": "english","teacher":"Marry"}, 
   {"class": "history","teacher":"Anne"},{"class": "history","teacher":"Bob"}
    {"class": "math","teacher":"Cathy"}]

我想找到分心class(列表中有多少个类):

['math','english','history']

我该怎么办?

4 个答案:

答案 0 :(得分:2)

from collections import OrderedDict
from operator import itemgetter

print(list(OrderedDict.fromkeys(map(itemgetter("class"),lis))))
['math', 'english', 'history']

答案 1 :(得分:1)

您可以使用set comprehension(假设您使用Python> = 2.7.6)并且如果顺序无关紧要:

distinct_class = {element['class'] for element in lis}
print list(distinct_class)
>> ['history', 'math', 'english']

答案 2 :(得分:1)

如果是新的类类型,您可以使用for循环迭代项目并将它们附加到列表中。

distinct_classes = []

for dist in lis:
    if dist['class'] not in distinct_classes:
        distinct_classes.append(dist['class'])

print distinct_classes

答案 3 :(得分:0)

您可以使用集合理解从列表中构建集合,从中提取每个class的{​​{1}}属性:

dict

如果需要,您可以使用>>> {x['class'] for x in lis} {'history', 'english', 'math'} 将此集转换为列表。

如果您想在删除重复项时保留订单,请参阅this question