我對Python和編程相對比較陌生,我試圖解決一個問題,它需要打印出兩個數字的差別== 2的數字。下面是我的嘗試:在比較2個元素時遍歷一個列表
l = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
k = []
count = 0
a = l[0] #initialize a to be the element in the first index
#b = l[1]
while (count < len(l)): #while count is less than length of list
for i in range(len(l)): #for each element i in l,
k.append(a) #append it to a new list k
a, b = l[i+1], l[i+1] #Now a and b pointers move to the right by 1 unit
count += 1 #update the count
print(k[i]) #print newly updated list k
if(a - b == 2): #attempting to get the difference of 2 from a,b. if difference a,b == 2, append them both
#If fail, move on to check the next 2 elements.
#k.append(l[i])
print(k)
代碼卡在a,b = l[i+1],l[i+1]
。爲了幫助您直觀地瞭解代碼的情況,請參考:http://goo.gl/3As1bD
感謝您的幫助!對不起,如果它有點凌亂。我想要做的就是能夠遍歷列表中的每個元素,同時比較它們之間的差異== 2
謝謝!展望替代
代碼給出行'A,B錯誤= 1 [i + 1],l [i + 1]'作爲列表索引超出範圍。當'i = len(l) - 1'時,你正在做'l [i + 1]'。除此之外,代碼中還有許多其他錯誤。 –