在 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)
这篇关于在项目列表上调用一个函数的最简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在python中的感兴趣区域周围绘制一个矩形How to draw a rectangle around a region of interest in python(如何在python中的感兴趣区域周围绘制一个矩形)
如何使用 OpenCV 检测和跟踪人员?How can I detect and track people using OpenCV?(如何使用 OpenCV 检测和跟踪人员?)
如何在图像的多个矩形边界框中应用阈值?How to apply threshold within multiple rectangular bounding boxes in an image?(如何在图像的多个矩形边界框中应用阈值?)
如何下载 Coco Dataset 的特定部分?How can I download a specific part of Coco Dataset?(如何下载 Coco Dataset 的特定部分?)
根据文本方向检测图像方向角度Detect image orientation angle based on text direction(根据文本方向检测图像方向角度)
使用 Opencv 检测图像中矩形的中心和角度Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 检测图像中矩形的中心和角度)