如果想在 V2EX 获得更好的推广效果,欢迎了解 PRO 会员机制:
https://www.v2ex.com/pro/about

如果你经常使用铜币置顶主题,持有 V2EX Solana Token 会在每日签到时获得额外铜币:
https://www.v2ex.com/solana
fanqieipnet
V2EX  ›  推广

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

  •  
  •   fanqieipnet · Jan 13, 2021 · 928 views
    This topic created in 1970 days ago, the information mentioned may be changed or developed.
    如何返回列表的累积汇总值?今天番茄加速就来讲一下。

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

       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)

      这个函数非常好用
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2888 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 14:32 · PVG 22:32 · LAX 07:32 · JFK 10:32
    ♥ Do have faith in what you're doing.