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

cleanest way to call one function on a list of items(在项目列表上调用一个函数的最简洁方法)
本文介绍了在项目列表上调用一个函数的最简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)