比较 python 中列表的元素

Compare the elements of a list in python

我想遍历一个列表并比较列表的元素。例如:第一个元素将与下一个元素进行比较。我有一个列表:

for i in range(len(a))
    for i+1 in range(len(a)) #check code
        if a[i] == a[i+1]
           a.pop(i+1)

有人可以在 python 中建议如何执行此操作吗?

第二个 元素开始,将每个元素与其前一个元素进行比较。

for ix in range(1, len(a)):
    compare_items(a[ix], a[ix - 1])

您没有按元素迭代列表(即 for el in a),这是一件好事,因为我相信修改您正在迭代的列表是行不通的。 但是,您的方法仍然存在缺陷,因为在循环开始时计算了一些元素 len(a) 并且索引没有考虑到您正在删除元素的事实,因此被检查的元素将引用弹出后列表中的位置(跳过元素和超出列表长度)。 您的示例使用临时列表 b:

以非常简单的方式重写
a=[1,3,3,6,3,5,5,7]

b=a[0:1]
for i in range(len(a)-1):
    print (a[i],a[i+1])
    if a[i]!=a[i+1]:
        b.append(a[i+1])
a=b

或一行版本:

from itertools import compress
list(compress(a,[x!=y for x,y in zip(a[:-1],a[1:])]))

无论如何,如果您的目的是删除列表中的连续重复项,您可以轻松地在 google 或堆栈溢出 'python remove consecutive duplicates from a list'.

上搜索
for this, next_one in zip(a, a[1:]):
    compare(this, next_one)

此解决方案是另一种可能适用于面临类似问题的人的替代方案

for i in range(len(nums)):
    for j in range(i+1, len(nums)):
        # Then the operation you want to carry out, e.g below
        if nums[i] + nums[j] == target:
            return(i,j)

其中 nums 是您正在迭代的列表的名称,ij 是您要比较的两个项目