比较同一列表中的两个相邻元素

Jam*_*mes 3 python list-comprehension list python-3.x

我已经通过了一个帖子,但我想知道在使用for循环时我的代码中出错了什么.

列表a如下:

a = [2, 4, 7,1,9, 33]
Run Code Online (Sandbox Code Playgroud)

我只想比较两个相邻的元素:

2 4
4 7
7 1
1 9
9 33
Run Code Online (Sandbox Code Playgroud)

我做了类似的事情:

for x in a:
    for y in a[1:]:
        print (x,y)
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 7

您的外循环会持续存在于内循环中的每个值.要比较相邻元素,您可以zip使用自身移位版本的列表.可以通过列表切片实现移位:

for x, y in zip(a, a[1:]):
    print(x, y)
Run Code Online (Sandbox Code Playgroud)

一般情况下,您的输入是任何可迭代而不是列表(或另一个支持索引的可迭代),您可以使用库中也提供的itertools pairwise配方more_itertools:

from more_itertools import pairwise

for x, y in pairwise(a):
    print(x, y)
Run Code Online (Sandbox Code Playgroud)


sop*_*ros 5

您正在将一个稳定元素与列表中的所有元素进行比较,但第一个元素除外。

正确的方法是:

for i in range(len(a)-1):
    x = a[i]
    y = a[i+1]
    print (x,y)
Run Code Online (Sandbox Code Playgroud)