python - 为什么我的功能代码比程序代码执行得更差?
问题描述
我正在尝试使用两个不同的函数来计算列表中的数字和单词。在这种情况下,它们都生成正确的输出。但我一直认为使用列表推导的函数式方法会比使用常规 for 循环的程序式方法做得更好。当我使用 timeit 比较它们时,我无法理解为什么函数式方法实际上表现更差。有人可以在这里指导我并解释我的实施是否有问题吗?
test = [14242, 'A XUTFN UVG V UFI', 98, 80273, 'CKE', 'CPR']
def proc_counter(A):
nums = 0
wrds = 0
for i in A:
if type(i) == str:
wrds += len(i.split())
else:
nums += 1
return "Count of words = {} and Count of numbers = {}".format(wrds, nums)
proc_counter(test)
#'Count of words = 7 and Count of numbers = 3'
def func_counter(A):
lst = [0 if type(elem) == int else len(elem.split()) for elem in A]
nums = collections.Counter(lst)[0]
wrds = sum(lst)
return "Count of words = {} and Count of numbers = {}".format(wrds,nums)
func_counter(test)
#'Count of words = 7 and Count of numbers = 3'
%timeit proc_counter(test)
#1.15 µs ± 2.46 ns per loop
%timeit func_counter(test)
#2.26 µs ± 14.5 ns per loop
解决方案
推荐阅读
- javascript - 循环遍历 jQuery 数组/将值输出到 div
- ethereum - 合同可以假装吗?
- php - Laravel 5.6 - 在日志/laravel.log ubuntu xenial 16.04 上的权限被拒绝
- eclipse - eclipse - 无法将选定的文本解析为定义的函数或成员
- java - Java 等效于 Kotlin 中的 arrayof()/listof()/setof()/mapof()
- class - 在 drupal 8 的标题区域添加自定义类
- asp.net-mvc - 使用实体属性进行数据验证
- c# - c#:如何自动更新服务?
- javascript - d3拖动功能返回错误
- c++ - CMake:如何清除目标编译选项