且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 map() 在对象列表上调用类方法

更新时间:2023-10-21 23:03:40

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).