从多个属性创建列表

时间:2013-07-18 14:54:59

标签: python list-comprehension

假设我有一个dicts或对象列表,实际上看起来像这样:

[
    {'score': 5, 'tally': 6},
    {'score': 1, 'tally': None},
    {'score': None, 'tally': None},
]

创建所有 '得分 '计数 列表的Pythonic和简洁方法是什么?那不是没有?所以结果如下:

[5, 6, 1 ]

2 个答案:

答案 0 :(得分:3)

使用列表推导来尝试这个简洁的解决方案:

lst = [{'score': 5, 'tally': 6},
       {'score': 1, 'tally': None},
       {'score': None, 'tally': None}]

[v for m in lst for v in m.values() if v is not None]
=> [6, 5, 1]

答案 1 :(得分:1)

list(i for i in 
     itertools.chain.from_iterable(
       itertools.izip_longest(
         (d['score'] for d in listOfDicts if d['score'] is not None), 
         (d['tally'] for d in listOfDicts if d['tally'] is not None)
     )) if i is not None)

>>> import itertools
>>> listOfDicts = [
...     {'score': 5, 'tally': 6},
...     {'score': 1, 'tally': None},
...     {'score': None, 'tally': None},
... ]
>>> list(i for i in itertools.chain.from_iterable(itertools.izip_longest((d['sco
re'] for d in listOfDicts if d['score'] is not None), (d['tally'] for d in listO
fDicts if d['tally'] is not None))) if i is not None)
[5, 6, 1]