比较同一列表中的两个相邻元素 [英] Compare two adjacent elements in same list

查看:214
本文介绍了比较同一列表中的两个相邻元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过帖子,但是我想知道在使用for循环时我在代码中做错了什么.

I have already gone through a post but I want to know what I did wrong in my code while using for loop.

列表a表示为:

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

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

All I want to compare two adjacent elements as :

2 4
4 7
7 1
1 9
9 33

我做了类似的事情:

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

推荐答案

您的外部循环在内部循环中持续存在 each 值.要比较相邻的元素,您可以 zip 带有本身的转换版本.可以通过列表切片:

Your outer loop persists for each value in your inner loop. To compare adjacent elements, you can zip a list with a shifted version of itself. The shifting can be achieved through list slicing:

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

general 情况下,您的输入是任何可迭代的,而不是列表(或支持索引的另一个可迭代),则可以使用

In the general case, where your input is any iterable rather than a list (or another iterable which supports indexing), you can use the itertools pairwise recipe, also available in the more_itertools library:

from more_itertools import pairwise

for x, y in pairwise(a):
    print(x, y)

这篇关于比较同一列表中的两个相邻元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆