如何比较同一列表中的两个相邻项 - Python

Ric*_*nny 4 python list python-2.7

我正在寻找一种比较列表中两个相邻项目的方法,例如.比较哪个值更高,然后我会相应地对它们进行排序.这是一个用户将要输入的列表,所以它不是公正的情况 if l[1] > l[2],因为我不知道列表的长度,所以我需要一个通用语句用于for循环.

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

编辑:我知道内置的排序功能,但只是想通过创建自己的:)来练习编码和算法编写

Ash*_*ary 19

你可以使用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
Run Code Online (Sandbox Code Playgroud)


Thi*_*ter 4

快速而丑陋的解决方案是这样的(不要使用它!):

for i, item in enumerate(lst):
    # here you can use lst[i + 1] as long as i + 1 < len(lst)
Run Code Online (Sandbox Code Playgroud)

但是,不要自己实现列表排序!用于.sort()就地排序或者sorted()如果您想创建一个新列表。python 网站上有一个关于如何对事物进行排序的非常好的指南。

如果这不是你的意图..而不是我上面发布的循环,还有一种更好的方法来迭代另一个 SO 问题中的列表中的块:

import itertools
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)
Run Code Online (Sandbox Code Playgroud)

你以前喜欢这样:

for x, y in grouper(2, lst):
    # do whatever. in case of an odd element count y is None in the last iteration
Run Code Online (Sandbox Code Playgroud)