简体   繁体   中英

How to get all seperate all equal pairs from a list in python

I'm trying to write a python program to find all equal pairs in a list. So if there is a single repeat of an element in a list it would be added to the list.

[2,2,2,2,2] would become [2,2]

[8,8,8,2] would become [8]

[8,16,16,8] would become [8,16]

[2,0,2,4] would become [2]

[0,0,2,2] would become [0,2]

So far i have tried nesting for loops.

def pairfinder(newlist):
pairlist = []
for idx in range(len(newlist)):
    for jdx in range(idx+1,len(newlist)):
        if newlist[idx] == newlist[jdx]:
            pairlist.append(newlist[idx])
            break
return pairlist

This gives me the correct answer on some cases.. but not all

Sorry for not being clear enough.

print [a for a,b in zip(my_list[::2],my_list[1::2]) if a == b]

you may need to sort my_list first ...

my_list = sorted(my_list)
print [a for a,b in zip(my_list[::2],my_list[1::2]) if a == b]

Im not at all sure this solves your issue.

def do_this_weird_thing(a_list):
    from itertools import groupby
    for grp,item in groupby(sorted(a_list)):
        item = list(item)
        yield [grp] * (len(item)//2)

from itertools import chain
print list(chain.from_iterable(do_this_weird_thing([2,0,2,4])))

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