我有这样一个简单的类
class MyClass():
def test(self):
print "Calling Test"
然后我创建一个列表:
lobj=[MyClass() for i in range (100)]
现在我想遍历 lobj
中的每个对象并调用它的方法 test()
。
我知道我可以使用 for
循环。但是,我想知道是否还有其他方法(只是为了避免列表比较大时的for循环)?例如
lobj[:].test()
最佳答案
...I wonder if there is any other way (just to avoid the for loop when the list is relatively large)?
是。您可以使用内置函数 map()
和一个 lambda 函数。如果您只想在每个元素上调用该方法,请执行以下操作:
map(lambda x:x.test(), lobj)
如果您想将结果存储在列表中:
v = map(lambda x:x.test(), lobj)
关于python - 迭代 python 列表对象并调用每个对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23775725/