簡體   English   中英

Python 組列表到子列表列表,這些列表是單調的,元素之間的差異相等

[英]Python group list to sub-lists lists that are monotonic with equal diff between elements

l = [2,4,6,12,14,16,21,27,29,31]

我想將它拆分為列表,這樣每個列表的元素都是一個單調列表,元素之間的差異為 2:

new_l = [[2,4,6], [12,14,16],[21], [27,29,31]]

執行此操作的最有效方法是什么?

更新
可以完全避免 Python 循環,只使用comprehensions (以及zip )來提高效率。 你可以這樣做:

l = [2,4,6,12,14,16,21,27,29,31, 44]
n = len(l)
#Find the splitting points (where the monotonic condition breaks):
splitting_points = [0] + [k for k in range(1, n) if l[k] - l[k - 1] != 2]
if splitting_points[-1] != n:
    splitting_points.append(n)
#Then split the list into intervals having bounds in the splitting_points:
new_l = [l[i: j] for i, j in zip(splitting_points[:-1], splitting_points[1:])]
print(new_l)

這“應該”比循環快得多(特別是對於大列表),但我沒有做過任何基准測試。

原來的
您必須迭代初始列表l ,維護具有當前單調序列的當前列表,並且每當新的迭代元素打破單調條件時,插入當前列表並清除它。
這是一個完全做到這一點的代碼:

l = [2,4,6,12,14,16,21,27,29,31]
new_l = []
current_l = [l[0]]                #initially, insert the first element
for k in range(1, len(l)):
    if l[k] - current_l[-1] == 2: #if the monotonic condition is satisfied
        current_l.append(l[k])    #we append the element
    else:
        new_l.append(current_l)   #otherwise, we append the previous list to the answer
        current_l = [l[k]]        #and clear the running sequence
new_l.append(current_l)           #there will always be a last sequence not appended to the answer
print(new_l)

您可以確定要拆分的索引,然后像這樣應用np.split

np.split(l, np.flatnonzero(np.diff(l)!=2) + 1)

輸出:

[array([2, 4, 6]), array([12, 14, 16]), array([21]), array([27, 29, 31])]

然而,使用不同長度的數組從來沒有效率,這就是np.split很慢的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM