簡體   English   中英

刪除列表中彼此距離小於 N 的元素

[英]Delete elements in list that are closer than N from each other

假設我有以下列表:

a = [0,5,10,11,15,22]

...而且我想確保列表元素之間的距離始終至少為 5,我該怎么做?

預期結果:

[0,5,10,15,22]

我嘗試的不是很pythonic:

a.sort()
prev_elem = a[0]
new_list = []
for elem in a[1:]:
    if abs(prev_elem-elem) >= 5:
         new_list.append(prev_elem)
    # update
    prev_elem = elem

編輯:在你投反對票之前:你為什么投反對票 請添加評論? 我在問一個問題並且我已經展示了我的作品,所以沒有理由拒絕投票。

您可以通過對現有代碼進行一些非常小的更改來實現。

更改的行在下面注釋。

a = [0,5,10,11,15,22]

a.sort()
prev_elem = a[0]
new_list = [prev_elem]  # <====== initialise with one element
for elem in a[1:]:
    if abs(prev_elem-elem) >= 5:
         new_list.append(elem)  # <===== append the new element
         prev_elem = elem  # <===== indented more (inside "if" block)

print(new_list)

這給出:

[0, 5, 10, 15, 22]

遍歷列表。 如果 arr[i]+5 > arr[i+1],則刪除 arr[i+1]。 類似於以下代碼。

i = 0
while i < len(arr)-1:
    if arr[i]+5 > arr[i+1]:
        del arr[i+1]
    else:
        i+=1

肯定有更清潔、更有效的方法來做到這一點,但這應該有效。

請注意,這是偽代碼,其中 n 是名為 arr 的數組的長度:

for i = 1 to n
    if (arr[i] - arr[i - 1] >= 5 OR arr[i] - arr[i - 1] <= -5)
        //remove arr[i]

一種方法:

a = [0,5,10,11,15,22]
result = []

for i, num in enumerate(a):
    if i == 0:
        result.append(num)
        continue
    if 3 <= abs(num - a[i-1]):
        result.append(num)

# [0,5,10,11,15,22] -> [0, 5, 10, 15, 22]
# [10, 9, 5, 0] -> [10, 5, 0]
# [10, 14, 9, 11, 5, 7, 0] -> [10, 14, 9, 5, 0]

編輯:

我意識到它可以做得更簡單。 使用切片和解包避免在空列表的情況下出現索引錯誤:

result = [*a[0:1]]      

for num in a[1:]:
    if 3 <= abs(num - result[-1]):
        result.append(num)

暫無
暫無

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

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