Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print all variable of class list without using for statement in python

Tags:

python

class

I put some classes(wow) in list a. And I want to print the variable num of all elements of a without using for statement. What should I do?

I want to(example):

[1,5,3,4,0] # Expected output

What I have tried:

import random as r

class wow():
    def __init__(self):
        self.num=r.randint(0,10)
a=[]
for x in range(5):
    a.append(wow())

print((lambda x: x)(a).num)
like image 758
kimhanuu Avatar asked Sep 09 '26 06:09

kimhanuu


2 Answers

You can add __str__() method to your class:

class wow(): 
    def __init__(self): 
        self.num=r.randint(0,10) 

    def __str__(self): 
        return str(self.num) 

then by just printing:

print(*a)

you will get:

3 9 4 9 3

in addition, reading this Link might be good for better clue:

like image 82
Mehrdad Pedramfar Avatar answered Sep 11 '26 18:09

Mehrdad Pedramfar


print(list(map(lambda x: x.num, a)))
like image 27
Artyom Vancyan Avatar answered Sep 11 '26 20:09

Artyom Vancyan