如何使用 map() 在对象列表上调用类方法 [英] How to use map() to call class methods on a list of objects

查看:59
本文介绍了如何使用 map() 在对象列表上调用类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对对象列表调用 object.method().

I am trying to call object.method() on a list of objects.

我已经试过了,但不能让它正常工作

I have tried this but can't get it to work properly

newList = map(method, objectList)

我收到错误 method is not defined 但我知道这是因为它是一个类方法而不是本地函数.

I get the error method is not defined but I know that is because it is a class method and not a local function.

有没有办法用 map() 或类似的内置函数来做到这一点?还是我必须使用生成器/列表推导式?

Is there a way to do this with map(), or a similar built in function? Or will I have to use a generator/list comprehension?

编辑您能否解释一下您的解决方案与使用此列表推导式的优势或对比?

edit Could you also explain the advantages or contrast your solution to using this list comprehension?

newList = [object.method() for object in objectList]

推荐答案

newList = map(method, objectList) 会在每个 上调用 method(object)objectlist 中的object.

newList = map(method, objectList) would call method(object) on each object in objectlist.

使用 map 执行此操作的方法需要一个 lambda 函数,例如:

The way to do this with map would require a lambda function, e.g.:

map(lambda obj: obj.method(), objectlist)

列表推导可能会略微更快,因为您不需要 lambda,它有一些开销(讨论了一下 此处).

A list comprehension might be marginally faster, seeing as you wouldn't need a lambda, which has some overhead (discussed a bit here).

这篇关于如何使用 map() 在对象列表上调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆