我正在努力撰寫一個 for 回圈,該回圈使用 if 陳述句將陣列“a”中的每個條目與前一個條目進行比較,并在值不同時記錄其在串列中的位置。陣列 a 是 1 和 - 1 的串列
陣列a=[1,1,1,1,-1,-1,-1,1,1,-1]等。它是隨機排序的 1 和 -1 的串列,因此它可能看起來像1,1,1,-1,-1,1,1,-1,-1,-1,-1, 1etc 所以基本上想找到與前一個不同的位置
我不完全確定您將如何做到這一點,因為我是 python 新手,所以任何幫助將不勝感激。謝謝
到目前為止,我只有
for i in range(len(a)):
if
uj5u.com熱心網友回復:
就像是
for i in range(1, len(a)):
if a[i] > a[i-1]:
#your code here
elif a[i-1] > a[i]:
#your code here
else:
#your code here
應該管用。
uj5u.com熱心網友回復:
可以使用 enumerate() 與您的 for 回圈進行比較
使用 enumerate() 與 List 中的上一個專案進行比較
a=[1,1,1,1,-1,-1,-1,1,1,-1]
for i, item in enumerate(a):
#Need to skip first element(when i==0) as a[-1] will return the last value in the array
if i > 0 and item == a[i-1]:
print(f"index {i} value:{item} is the same as previous index {i-1}")
結果:
index 1 value: 1 is the same as previous index 0
index 2 value: 1 is the same as previous index 1
index 3 value: 1 is the same as previous index 2
index 5 value:-1 is the same as previous index 4
index 6 value:-1 is the same as previous index 5
index 8 value: 1 is the same as previous index 7
uj5u.com熱心網友回復:
嘗試這個:
[i for i in range(1, len(a)) if a[i-1] != a[i]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/452783.html
上一篇:C中生成解密密鑰的RSA演算法
