【问题标题】:Finding Deltas - Difference between elements in a Python list查找增量 - Python 列表中元素之间的差异
【发布时间】:2013-04-21 16:14:27
【问题描述】:

我有这段代码可以在列表中查找连续的数字:

from itertools import groupby
from operator import itemgetter

a = [1,2,3,5,55,56]

def consc(b):
  for k, g in groupby(enumerate(b), lambda (i,x):i-x):
     print map(itemgetter(1), g)  

consc(a)

输出:

[1, 2, 3]
[5]
[55, 56]

但是,我也希望能够寻找其他增量(1 到 10),例如 2 的差异将在同一个列表中产生以下输出:

[1]
[2]
[3,5]
[55]
[56]

谢谢!

【问题讨论】:

    标签: python list delta


    【解决方案1】:

    其实是一个很简单的修改:

    from itertools import groupby, count
    from operator import itemgetter
    
    a = [1,2,3,5,55,56]
    
    def consc(b, step):
      for k, g in groupby(zip(count(step=step), b), lambda (i, x): i-x):
         print map(itemgetter(1), g)
    
    consc(a, 2)
    

    这给出了:

    [1]
    [2]
    [3, 5]
    [55]
    [56]
    

    我们不使用enumerate(),而是使用zip()count() 以及所需值的步长,从而得到想要的结果。

    稍微整理一下:

    from itertools import groupby, count
    from operator import itemgetter
    
    def _sub(item):
        a, b = item
        return a - b
    
    def consecutive(iterable, step):
        for _, g in groupby(zip(count(step=step), iterable), _sub):
            yield map(itemgetter(1), g)
    
    a = [1, 2, 3, 5, 55, 56]
    
    print(list(consecutive(a, 2)))
    

    在这里有一个生成器并使用更具描述性的名称是有意义的。使用实际函数可以避免每次使用函数时都重新声明它,就像lambda 一样。通过避免使用已从语言中删除的参数解包,这也适用于 Python 3.x。

    【讨论】:

    • 我比我想的更喜欢这个,就是用i*step-x代替i-x
    猜你喜欢
    • 2011-01-24
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多