最简单的方法来调用项目列表上的一个函数 [英] cleanest way to call one function on a list of items

查看:150
本文介绍了最简单的方法来调用项目列表上的一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python 2中,我使用 map 将函数应用于多个项目,例如,删除与模式匹配的所有项目:

In python 2, I used map to apply a function to several items, for instance, to remove all items matching a pattern:

map(os.remove,glob.glob("*.pyc"))

当然我忽略 os.remove 的返回码,我只想删除所有文件。它创建了一个列表的临时实例,但它确实有效。

Of course I ignore the return code of os.remove, I just want all files to be deleted. It created a temp instance of a list for nothing, but it worked.

使用Python 3,因为 map 返回一个迭代器而不是一个列表,上面的代码什么都不做。
我找到了解决方法,因为 os.remove 返回,我使用任何强制迭代完整列表,而不创建列表(更好的性能)

With Python 3, as map returns an iterator and not a list, the above code does nothing. I found a workaround, since os.remove returns None, I use any to force iteration on the full list, without creating a list (better performance)

any(map(os.remove,glob.glob("*.pyc")))

但它似乎有点危险,特别是在将它应用于返回某些东西的方法时。另一种方法是使用单行而不创建不必要的列表?

But it seems a bit hazardous, specially when applying it to methods that return something. Another way to do that with a one-liner and not create an unnecessary list?

推荐答案

map()(以及从2.7到3.x的许多其他函数)返回生成器而不是列表是一种节省内存的技术。对于大多数情况,更正式地写出循环没有性能损失(它甚至可能是可读性的首选)。

The change from map() (and many other functions from 2.7 to 3.x) returning a generator instead of a list is a memory saving technique. For most cases, there is no performance penalty to writing out the loop more formally (it may even be preferred for readability).

我会提供一个例子,但@vaultah在评论中钉了它:仍然是一行:

I would provide an example, but @vaultah nailed it in the comments: still a one-liner:

for x in glob.glob("*.pyc"): os.remove(x)

这篇关于最简单的方法来调用项目列表上的一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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