liren.jin
liren.jin

Reputation: 3

How to Get a List of Class Attribute

there is a list of instances from the same class, and i want to extract a certain attribute of every instance and build up a new list

class Test:
    def __init__(self, x):
        self.x = x

l = [Test(1), Test(2), Test(3), Test(4)]

something like that, and i want to get a list which result is [1, 2, 3, 4]

Upvotes: 0

Views: 29

Answers (1)

The best way to do it would probably be like this:

class Test:
    def __init__(self, x):
        self.x = x

l = [Test(1), Test(2), Test(3), Test(4)]
res = [inst.x for inst in l] # [1, 2, 3, 4]

or just do it from the start:

l = [Test(1).x, Test(2).x, Test(3).x, Test(4).x]

Upvotes: 2

Related Questions