【问题标题】:Create a list from multiple attributes从多个属性创建列表
【发布时间】:2013-07-18 14:54:59
【问题描述】:

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

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

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

[5, 6, 1 ]

【问题讨论】:

    标签: python list-comprehension


    【解决方案1】:

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

    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]
    

    【讨论】:

    • 这真是太好了,谢谢!如果列表中的元素不是字典,你知道类似的方法吗?即scoretally 将是对象的属性。
    • 类似,因为对象中的属性存储在对象的__dict__属性中
    • 请注意,如果值为 0 或空字符串等,则此特定解决方案不会报告。其他不是“假”的值无。要找到这些,请将列表理解更改为:[v for m in lst for v in m.values() if v is not None]
    • @brechin 你是对的,最好谨慎行事。我更新了我的答案,谢谢!
    【解决方案2】:
    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]
    

    【讨论】:

    • 谢谢,我从来不知道izip_longest。这类似于我的解决方案最终的结果,我只是觉得我错过了单行列表理解。
    • 是的,izip_longest 非常有用。签出this
    • 乐于助人!附带说明一下,用我的真名称呼真是令人耳目一新。通常,每个人都只是通过他们的用户名来指代其他人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2016-09-15
    • 2020-08-04
    • 1970-01-01
    • 2021-07-28
    相关资源
    最近更新 更多