簡體   English   中英

當連續列表元素的數量具有唯一值時停止處理

[英]Stop processing when the number of consecutive list elements have a unique value

我有很長的列表格式的數據記錄,我想根據特定條件分隔該記錄。 我想獲得列表元素的總和,因此當連續 3 個或更多元素等於 0 時,總和順序將停止,然后總和順序從停止的位置重新開始。

例如:列表的一部分是 [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 6, 0]

output 應該是 [14, 8, 6] 的新列表,其中: output1: 8 + 2 + 1 + 1 + 2 = 14, output2: 6 + 2 = 8, output3: 6

到目前為止,我寫了類似下面的內容,但我有兩個問題:1- 列表索引超出范圍,2- 列表末尾有三個 0 元素的假列表擴展

# note: i add three fake 0 at the end of the list to get the correct output
arr = [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 6, 0, 0, 0, 0]
result = []
cum = 0        
for i in range(0, len(arr)):
   el, el1, el2 = arr[i], arr[i+1], arr[i+2]
   if el != 0:
       cum = cum + el
   if el == 0 and el1 == 0 and el2 == 0: 
       if cum != 0:
          result.append(cum)
          cum = 0

這將解決您的兩個問題:

arr = [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 6, 0]
    result = []
    cum = 0
    for i in range(0, len(arr) - 2):
        el, el1, el2 = arr[i], arr[i + 1], arr[i + 2]
        if el != 0:
            cum = cum + el
        if el == 0 and el1 == 0 and el2 == 0:
            if cum != 0:
                result.append(cum)
                cum = 0
        elif i == len(arr) - 3:
            cum = el + el1 + el2
            result.append(cum)
            break

    print(result)

'elif i == len(arr) - 3:' 條件可確保在達到最后 3 個元素時循環中斷。 此外,僅當最后三個元素中至少有 1 個元素非零時才會執行。

用這個:

a = [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 6, 0, 0, 0, 0]
total_list = []
i = 0
sum = 0
for ind, ele in enumerate(a):
  if ind < (len(a) - 2):
    sum += ele
    if (a[ind] == 0) and (a[ind+1] == 0) and (a[ind+2] == 0):
      if sum != 0:
        total_list.append(sum)
        sum = 0
  else:
    sum += ele
    if sum != 0:
      total_list.append(sum)
      sum = 0

print(total_list)
arr = [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 6, 0, 0, 0, 0]
result = []
cum = 0        
for i in range(0, len(arr)-2):
   el, el1, el2 = arr[i], arr[i+1], arr[i+2]
   if el != 0:
       cum = cum + el
   if el == 0 and el1 == 0 and el2 == 0: 
       if cum != 0:
          result.append(cum)
          cum = 0
print(result)
arr = [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 6, 0, 0, 0]
result = []
cum = 0
zeros = 0
for i in range(0, len(arr)):
   el = arr[i]
   if el != 0:
       cum = cum + el
       zeros = 0
   if el == 0:
        zeros += 1
        if cum != 0 and zeros == 3:
            result.append(cum)
            cum = 0

您可以使用變量來跟蹤您在數組中遇到的 0 的數量,這不會消除在數組末尾“附加”三個 0 的問題,這可以通過在開頭添加 arr.extend( [0,0,0])

暫無
暫無

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

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