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

标签 python list

我有这样一个简单的类

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/

相关文章:

javascript - Django 和 Dropzone.js

php - 在windows下从php执行python脚本

python - append 到列表仅 append 第一项

python - 如何过滤数据框中的列表列?

c++ - Cython 为 libcpp.list 赋值

python - python 从模块导入哪些属性?

php - 将 PHP 和 Sql 与 Python 混合使用

python - pydoc 将 python 子模块内容注入(inject)主模块

python - 将字典值分配给变量,其中 key == list[element]

r - 如何在 switch 语句中将向量作为参数传递