简体   繁体   中英

Compare the elements of a list in python

I want to iterate through a list and want to compare the elements of list. For example: First element will be compared with next element. I've a list a:

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)

Can anybody suggest how to do this in python?

You are not iterating over the list by element (ie for el in a ), that is a good thing because I believe modifying a list over which you are iterating wouldn't work. However your approach still has a flaw, in the sense that a number of elements len(a) is calculated at the beginning of the loop and the index doesn't keep into account the fact that you are removing elements, so the inspected element will refer to the position in the list after the pop (skipping elements and exceeding list length). Your example rewritten in a quite straightforward way using a temporary list 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

Or a one line version:

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

Anyway if your purpose was to remove consecutive duplicate items in a list, you could easily search on google or on stack overflow 'python remove consecutive duplicates from a list'.

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

Starting with the second element, compare each element to its predecessor.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM