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

Viewed 161

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)
4 Answers
print(list(map(lambda x: x.num, a)))

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:

I don't recommend this, but you can use map with a lambda function.

import random as r

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

_ = list(map(lambda x: print(x.num, end=' '), a))
# prints:
2 8 0 6 5

You can also use a while loop and catch the StopIteration.

g = iter(a)
while True:
    try:
        print(next(g).num, end=' ')
    except StopIteration:
        break

You might harness operator.attribgetter for that task following way:

import operator
import random
class wow:
    def __init__(self):
        self.num=random.randint(0,10)
a=[]
for x in range(5):
    a.append(wow())
print(*map(operator.attrgetter('num'),a))

Output:

4 3 9 8 8
Related