1

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

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

什么是一种 Pythonic 和简洁的方法来创建所有不是 None的'score's'tally's的列表?所以结果如下:

[5, 6, 1 ]
4

2 回答 2

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]
于 2013-07-18T15:00:58.233 回答
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]
于 2013-07-18T14:57:47.907 回答