迭代python列表对象并调用每个对象的方法

2024-04-18 09:37:36 发布

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

我有这样简单的课

class MyClass():
    def test(self):
      print "Calling Test"

然后我创建一个列表:

lobj=[MyClass() for i in range (100)]

现在我想迭代lobj中的每个对象并调用其medthod test()。 我知道我可以使用for循环。但是,我想知道是否还有其他方法(只是在列表相对较大时避免for循环)?例如

lobj[:].test()

Tags: 对象intestself列表fordefmyclass
2条回答

...I wonder if there is any other way (just to avoid the for loop when the list is relatively large)?

。您可以使用内置函数^{}和lambda函数。如果只想对每个元素调用方法,请执行以下操作:

map(lambda x:x.test(), lobj)

如果要将结果存储在列表中:

v = map(lambda x:x.test(), lobj)

最好的办法是:

[i.test() for i in lobj]

这将调用该方法,但不会将结果存储在任何位置,因此在为所有实例调用该方法之后,列表将被丢弃。你知道吗

相关问题 更多 >