我的問題有點難以描述,我想用一個例子來說明我的問題。
比如每個數字對應一個對應的值,
a=[0,3,5]
b=[0,1,2,3,4,5,6,7]
for i in range(b):
if i not in a:
if ***value of i < value of next i that meet the condition***
a.append(i)
else:
a.append(***next i that meet the condition***)
我想寫這樣的代碼,但問題是我不知道如何表達下一個滿足條件的 i。簡單地使用 i 1 肯定是錯誤的。有人可以幫助我嗎?非常感謝你們!!
uj5u.com熱心網友回復:
調整回圈的范圍可以更輕松地訪問 的當前和下一個元素b:
a = [0, 3, 5]
b = [0, 1, 12, 2, 16, 3, 18, 4, 20, 5, 22]
for index in range(1, len(b) - 1):
current_item = b[index - 1]
next_item = b[index]
if current_item in a:
continue
if current_item < next_item:
a.append(current_item)
else:
continue
print(a)
出去:
[0, 3, 5, 1, 2, 4]
uj5u.com熱心網友回復:
你沒有提到額外的限制,所以沒有檢查我們的串列是空的還是只包含 1 個元素。
你可以考慮使用這個:
a = [0, 3, 5]
b = [0, 1, 2, 3, 4, 5, 6, 7]
for i in range(len(b) - 1):
if (b[i] < b[i 1]) and b[i] not in a:
a.append(b[i])
print(a)
如果您不想使用“i 1”,這是另一個版本:
a = [0, 3, 5]
b = [0, 1, 2, 3, 4, 5, 6, 7]
for n, m in zip(b[:-2], b[1:]):
if n < m and n not in a:
a.append(n)
print(a)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388561.html
標籤:Python 列表 python-2.7 循环
