在python中不使用for语句打印类列表的所有变量

2024-05-16 08:13:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一些类(wow)放在列表a中。 我想打印a的所有元素的变量num,而不使用for语句。 我该怎么办

我想(举例):

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

我所尝试的:

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)

Tags: importself元素列表foroutputdefas
3条回答
print(list(map(lambda x: x.num, a)))

您可以向类中添加__str__()方法:

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

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

然后只需打印:

print(*a)

您将获得:

3 9 4 9 3

此外,阅读此Link可能有助于获得更好的线索:

我不建议这样做,但您可以将map与lambda函数一起使用

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

您还可以使用while循环并捕获StopIteration

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

相关问题 更多 >