3

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)
1
  • 2
    Why don't you want to use for? Commented Jun 13, 2020 at 10:59

4 Answers 4

3

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, this is definitely the best answer.
2
print(list(map(lambda x: x.num, a)))

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.