简体   繁体   English

具有 class 属性的列表理解

[英]List comprehension with class attributes

I want to use class attributes to make a single list of all attributes:我想使用 class 属性来列出所有属性:

from dataclasses import dataclass

@dataclass
class Foo:
    a: int
    b: int

data = [
    Foo(1,2),
    Foo(3,4)
]
print([[foo.a, foo.b] for foo in data])

But the result is a list of lists of attributes.但结果是属性列表的列表。 How can I have a single list containing all attributes [1,2,3,4] instead of [[1,2],[3,4]] ?如何拥有一个包含所有属性[1,2,3,4]而不是[[1,2],[3,4]]的列表?

I would recommend you to use itertools.chain.from_iterable to flatten the intermediate list我建议您使用itertools.chain.from_iterable来展平中间列表

In [6]: import itertools

In [7]: print(list(itertools.chain.from_iterable([[foo.a, foo.b] for foo in data])))                                                                                                                               
[1, 2, 3, 4]
from functools import reduce 
from dataclasses import dataclass

@dataclass
class Foo:
  a: int
  b: int

data = [
  Foo(1,2),
  Foo(3,4)
]

result = [[foo.a, foo.b] for foo in data]
print(reduce(list.__add__, result))

Just use nested list comprehension只需使用嵌套列表理解

[x for x in [foo.a, foo.b] for foo in data]

You could do something like:您可以执行以下操作:

print([value for foo in data for attr, value in foo.__dict__.items()])

It's basically doing two for loops, the same as doing:它基本上是在做两个 for 循环,和做的一样:

for foo in data:
    for attr, value in foo.__dict__.items():
        print(value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM