在比较2个元素时遍历列表

时间:2016-01-20 05:05:05

标签: python list python-3.x

我对python和编程比较陌生,我正在尝试解决一个问题,需要打印出两个数字差异= = 2的数字对。这是我的尝试:< / p>

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

谢谢!期待替代品

3 个答案:

答案 0 :(得分: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 :(得分: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

要解决此问题,您应该循环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]

答案 2 :(得分:0)

为什么不进行双嵌套for循环:

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)