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

时间:2018-12-04 11:14:24

标签: python python-3.x list list-comprehension

我已经经历过post,但是我想知道在使用for循环时我在代码中做错了什么。

列表a表示为:

a = [2, 4, 7,1,9, 33]

我想将两个相邻元素进行比较:

2 4
4 7
7 1
1 9
9 33

我做了类似的事情:

for x in a:
    for y in a[1:]:
        print (x,y)

2 个答案:

答案 0 :(得分:7)

您的外循环在您的内循环中持续存在 each 值。要比较相邻的元素,您可以zip本身具有偏移版本的列表。可以通过list slicing实现转移:

HTTP ERROR 403
Problem accessing /cluster. Reason:

    GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
Powered by Jetty://

general 情况下,您的输入是任何可迭代的,而不是列表(或支持索引的另一个可迭代),则可以使用itertools pairwise recipe,也可以在{{ 3}}库:

for x, y in zip(a, a[1:]):
    print(x, y)

答案 1 :(得分:3)

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

正确的方法是:

for i in range(len(a)-1):
    x = a[i]
    y = a[i+1]
    print (x,y)
相关问题