Python 在比较两个元素时遍历列表
我对python和编程比较陌生,我正在尝试解决一个问题,这个问题需要打印出两个数字的差==2的数字对。以下是我的尝试:Python 在比较两个元素时遍历列表,python,list,python-3.x,Python,List,Python 3.x,我对python和编程比较陌生,我正在尝试解决一个问题,这个问题需要打印出两个数字的差==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 (co
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)
l=[1,2,3,5,7,11,13,17,19,23]
k=[]
计数=0
a=l[0]#将a初始化为第一个索引中的元素
#b=l[1]
while(count
代码卡在a,b=l[i+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)]
您可以简单地执行
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)]
为什么不执行双嵌套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)
为什么不执行双嵌套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)
问题是,您正在迭代
范围(len(l))
并试图通过l[i+1]
获取前面的项,这使您得到一个索引器
:
例如:
>>> 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
问题是,您正在迭代
范围(len(l))
并试图通过l[i+1]
获取前面的项,这使您得到一个索引器
:
例如:
>>> 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
代码在
a,b=l[i+1],l[i+1]
行中给出错误,因为列表索引超出范围。当i=len(l)-1
时,您正在执行l[i+1]
。除此之外,您的代码中还有许多其他错误。由于列表索引超出范围,代码在a,b=l[i+1],l[i+1]
行中给出了一个错误。当i=len(l)-1
时,您正在执行l[i+1]
。除此之外,您的代码中还有许多其他错误。哇!太棒了。虽然我还没有学会zip,谢谢!哇!太棒了。虽然我还没有学会zip,谢谢!好主意,但它会打印双份!像3,5和5,3好主意,但它打印出双倍!像3,5和5,3冰!但它不断循环以附加到列表k中。我试图比较索引中的两个元素,以检查差异是否为2。还是拿不到。我正在努力。再次感谢,很好!但它不断循环以附加到列表k中。我试图比较索引中的两个元素,以检查差异是否为2。还是拿不到。我正在努力。再次感谢。