如何比较同一列表中的两个相邻项目-Python [英] How to compare two adjacent items in the same list - Python

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

问题描述

我正在寻找一种比较列表中两个相邻项目的方法,例如比较哪个具有更高的价值,然后我将对它们进行相应的排序.这是用户将要输入的列表,因此不只是 if l[1] > l[2],因为我不知道列表的长度,所以 我需要在for循环中使用的一般声明.

I am searching for a way to compare two adjacent items in a list, eg. comparing which has a higher value, and then I will sort them accordingly. It is a list the user will be inputting, so it is not a case of just if l[1] > l[2], as I will not know the length of the list, so I will need a general statement for use in a for loop.

我有个类似的想法 for i in l: if x > i[index of x + 1] 但是不知道如何找到变量的索引. 任何帮助表示感谢,谢谢

I had the idea of having something akin to for i in l: if x > i[index of x + 1] but do not know how to find the index of the variable. Any help appreciated, Thank you

我知道内置的排序功能,但是只想通过创建自己的:)

I am aware of the built in sort function, but just wanted to practice coding and algorithm-writing by creating my own :)

推荐答案

您可以使用 zip() :

You can use zip():

In [23]: lis = [1,7,8,4,5,3]

In [24]: for x, y in zip(lis, lis[1:]):
   ....:     print x, y           # prints the adjacent elements
             # do something here
   ....:     
1 7
7 8
8 4
4 5
5 3

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

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