在项目列表上调用一个函数的最简洁方法

2022-01-10 00:00:00 python python-3.x iterator

问题描述

在 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 返回 None,我使用 any 强制对完整列表进行迭代,而不创建 列表(性能更好)

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)

相关文章