2016-01-20 75 views
0

我對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

謝謝!展望替代

+1

代碼給出行'A,B錯誤= 1 [i + 1],l [i + 1]'作爲列表索引超出範圍。當'i = len(l) - 1'時,你正在做'l [i + 1]'。除此之外,代碼中還有許多其他錯誤。 –

回答

2

你可以簡單地做

l = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23] 
[(i,j) for i,j in zip(l,l[1:]) if abs(i-j)==2] 

輸出:[(3, 5), (5, 7), (11, 13), (17, 19)]

+1

哇!太棒了。雖然我還沒有學習拉鍊,謝謝! – misheekoh

0

爲什麼不循環做一個雙重嵌套:

l = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23] 
for i in l: 
    for j in l: 
     if abs(i-j) == 2: 
      print(i, j) 
+0

好主意,但它打印出雙打!像3,5和5,3 – misheekoh

2

的問題是,你迭代range(len(l)),並試圖通過l[i+1]得到前面的項目,這使你得到一個IndexError

例如:

>>> l = [1,2,3] 
>>> 
>>> l[len(l)+1] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: list index out of range 

對於這個問題的GET騎你應該遍歷range(len(l)-1)和第一個項目使用l[i]

for i in range(len(l)-1): #for each element i in l, 
       k.append(a)   #append it to a new list k 
       a, b = l[i], l[i+1] 
+0

不錯!但它保持循環以追加到列表k中。我試圖比較索引中的兩個元素來檢查差異是否爲2.仍然無法得到它。我在做這個工作。再次感謝。 – misheekoh