首页 > 解决方案 > 为什么我的功能代码比程序代码执行得更差?

问题描述

我正在尝试使用两个不同的函数来计算列表中的数字和单词。在这种情况下,它们都生成正确的输出。但我一直认为使用列表推导的函数式方法会比使用常规 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

标签: pythonfunctional-programmingtimeit

解决方案


推荐阅读