我是靠谱客的博主 务实身影,最近开发中收集的这篇文章主要介绍列表表达式同filter和map的比较,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

filter和map合起来能做的事情,列表推导也可以做,如下:

import timeit
TIMES = 10000
SETUP = """
symbols = '$¢£¥€¤'
def non_ascii(c):
return c > 127
"""
def clock(label, cmd):
res = timeit.repeat(cmd, setup=SETUP, number=TIMES)
print(label, *('{:.3f}'.format(x) for x in res))
clock('listcomp
:', '[ord(s) for s in symbols if ord(s) > 127]')
clock('listcomp + func :', '[ord(s) for s in symbols if non_ascii(ord(s))]')
clock('filter + lambda :', 'list(filter(lambda c: c > 127, map(ord, symbols)))')
clock('filter + func
:', 'list(filter(non_ascii, map(ord, symbols)))')
listcomp
: 0.012 0.013 0.017
listcomp + func : 0.022 0.020 0.018
filter + lambda : 0.021 0.021 0.021
filter + func
: 0.024 0.020 0.019

map/filter的组合也不必列表表达式要快。

最后

以上就是务实身影为你收集整理的列表表达式同filter和map的比较的全部内容,希望文章能够帮你解决列表表达式同filter和map的比较所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(83)

评论列表共有 0 条评论

立即
投稿
返回
顶部