V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
fanqieipnet
V2EX  ›  推广

如何返回列表的累积汇总值?

  •  
  •   fanqieipnet · 2021-01-13 17:55:12 +08:00 · 495 次点击
    这是一个创建于 1170 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如何返回列表的累积汇总值?今天番茄加速就来讲一下。

      返回列表的累积汇总值,原型:

       accumulate(iterable[, func, *, initial=None])

      应用如下:

       In [36]: list(accumulate([1,2,3,4,5,6],lambda x,y: x*y))

       Out[36]: [1, 2, 6, 24, 120, 720]

       accumulate 大概的实现代码如下:

       def accumulate(iterable, func=operator.add, *, initial=None):

       it = iter(iterable)

       total = initial

       if initial is None:

       try:

       total = next(it)

       except StopIteration:

       return

       yield total

       for element in it:

       total = func(total, element)

       yield total

      以上代码,你还好吗?与 chain 简单的 yield 不同,此处稍微复杂一点,yield 有点像 return,所以 yield total 那行直接就返回一个元素,也就是 iterable 的第一个元素,因为任何时候这个函数返回的第一个元素就是它的第一个。又因为 yield 返回的是一个 generator 对象,比如名字 gen,所以 next(gen)时,代码将会执行到 for element in it:这行,而此时的迭代器 it 已经指到 iterable 的第二个元素,OK,相信你懂了!

      漏斗筛选

      它是 compress 函数,功能类似于漏斗功能,所以我称它为漏斗筛选,原型:

       compress(data, selectors)

       In [38]: list(compress('abcdefg',[1,1,0,1]))

       Out[38]: ['a', 'b', 'd']

      容易看出,compress 返回的元素个数等于两个参数中较短的列表长度。

      它的大概实现代码:

       def compress(data, selectors):

       return (d for d, s in zip(data, selectors) if s)

      这个函数非常好用
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1339 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:37 · PVG 07:37 · LAX 16:37 · JFK 19:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.