[英]Basic Python - finding difference between elements in a list - IndexError
[英]Finding Deltas - Difference between elements in a Python list
我有這段代碼可以在列表中查找連續數字:
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]
謝謝!
這實際上是一個非常簡單的修改:
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.