[英]Iterating over two lists at the same time and try to find if a number in one list is bigger than items in the other list
(對不起,如果我的標題令人困惑。我不知道如何描述這個問題)
我有以下格式的兩個列表:
list_a = [[10, 1], [25, 2]] # list sorted base on the first element of each pair
list_b = [3, 14, 5, 26]
我想看看在list_b
的項目總和大於list_a[i][0]
,如果是這樣,將list_a[i][1]
到總和中。 想想玩游戲並獲得list_b
的積分,並在達到list_a
指定的特定積分時獲得獎勵積分。
我的預期輸出是一個數字序列。 對於上面的例子:
# [3, 3+14+1, 3+14+1+5, 3+14+1+5+26+2]
# 3+14+1 because 3+14 is greater than 10
# 3+14+1+5+26+2 because 3+14+1+5+26 is greater than 25
[3, 18, 23, 51]
我的嘗試:
sum_b = 0 # used to track sum of items in list_b
output_list = []
for i in list_a:
for j in list_b:
# go over list b to get current sum
sum_b += j
if sum_b > i[0]: # when I see sum_b > i[0], I add i[1] to sum_b
sum_b += i[1]
output_list.append(sum_b)
# I want to keep going through the list to see when sum_b gets greater than 25 and add 2 to sum_b
使用更新的 questoin,您似乎想要找到list_b
的累積總和,並在滿足條件時添加內部list_a
的第二個元素。 我建議首先編譯list_b
的累積總和列表,然后交叉檢查list_a
並添加滿足要求的每個第二個元素:
cumsum_b = [sum(list_b[:i+1]) for i in range(len(list_b))]
# [3, 17, 22, 48]
result = []
for s in cumsum_b:
for n, i in list_a:
if s > n:
s += i
result.append(s)
# [3, 18, 23, 51]
接近你自己的嘗試,但正確地通過list_a
推進你的i
。 這里i
始終是下一個未使用的list_a
對(如果沒有剩余, list_a
None
),並且我在通過list_b
循環期間在正確的點使用它。
sum_b = 0 # used to track sum of items in list_b
output_list = []
iter_a = iter(list_a)
i = next(iter_a, None)
for j in list_b:
# go over list b to get current sum
sum_b += j
if i and sum_b > i[0]: # when I see sum_b > i[0], I add i[1] to sum_b
sum_b += i[1]
i = next(iter_a, None)
output_list.append(sum_b)
它只需要線性時間,因為我並行地瀏覽兩個列表而不是嵌套的全長循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.