假設我有一個像這樣的浮動串列:
00000.0001
00000.0002
00000.0003
00000.0004
00001.0009
12345.0015
12345.0016
12345.0017
12345.0018
12345.0019
12346.0010
54321.0021
54321.0022
54321.0023
我的目標是在一個范圍內對每個組的第一個和最后一個元素求和,在我的情況下,如果它最大加 1,例如:
00000.0001 00001.0009
12345.0015 12346.0010
54321.0021 54321.0023
我試圖根據陣列的長度使用 zip 和 range 迭代陣列,首先存盤組的第一個元素,但不能完全確定解決方案。
我對大熊貓了解不多,但這有幫助嗎?任何其他提示將不勝感激,不一定需要確切的解決方案。
uj5u.com熱心網友回復:
只需遍歷串列并跟蹤您越過閾值的頻率。記錄您上次越過該值時的值并將它們相加。
things = [1,2,3,4,10,11,12,21,22,23]
start = things[0]
threshold = 10
totals=[]
for i, n in enumerate(things):
if n - start >= threshold:
totals.append(start things[i-1])
start = n
if start != n:
totals.append(start n)
else:
totals.append(n)
print(totals)
assert sum(totals) == (1 10) (11 12) (21 23)
uj5u.com熱心網友回復:
您可以使用 zip 來識別與其前任相距超過 1.0(閾值)的元素。對這些中斷應用累積總和將產生可與 groupby() 一起使用的組識別符號:
L = [0.0001,
0.0002,
0.0003,
0.0004,
1.0009,
12345.0015,
12345.0016,
12345.0017,
12345.0018,
12345.0019,
12346.0010,
54321.0021,
54321.0022,
54321.0023]
from itertools import groupby,accumulate
threshold = 1.0
groups = accumulate(b-a>threshold for a,b in zip(L[:1] L,L))
result = [ (g[0],g[-1]) for g,g[:] in groupby(L,lambda _:[next(groups)]) ]
print(result)
[(0.0001, 0.0004),
(1.0009, 1.0009), # 1.0009 - 0.0004 = 1.0005 > 1.0
(12345.0015, 12346.001),
(54321.0021, 54321.0023)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399334.html
上一篇:如何設定欄位值過期時間?
