简体   繁体   中英

Compare items in list if tuples Python

If have this list of tuples:

l1 = [('aa', 1),('de', 1),('ac', 3),('ab', 2),('de', 2),('bc', 4)]

I want to loop over it, and check if the second item in each tuple is the same as another second item in a tuple in this list. If it is, I want to put this tuple in a new list of tuples.

So from this list of tuples I would expect for my new list of tuples:

l2 = [('aa', 1), ('de', 1), ('ab', 2),('de', 2)]

Because the one's and the two's match. Right now if have this:

l2 = []
for i in range(len(l1)):
    if l1[i][1] in l1[:][0]:
        l2.append(l1[i])

However, this only gives me:

l2 = [('aa', 1), ('de', 1)]

I'm pretty sure I'm not indexing the list of tuples right. The solution is probably pretty simple, but I'm just not getting there.

You'll need two passes: one to count how many times the second element exists, and another to then build the new list based on those counts:

from collections import Counter

counts = Counter(id_ for s, id_ in l1)
l2 = [(s, id_) for s, id_ in l1 if counts[id_] > 1]

Demo:

>>> from collections import Counter
>>> l1 = [('aa', 1),('de', 1),('ac', 3),('ab', 2),('de', 2),('bc', 4)]
>>> counts = Counter(id_ for s, id_ in l1)
>>> [(s, id_) for s, id_ in l1 if counts[id_] > 1]
[('aa', 1), ('de', 1), ('ab', 2), ('de', 2)]

Your code goes wrong with l1[:][0] ; l1[:] just creates a shallow copy of the list, then takes the first element from that list. Even if it worked, your approach would have to check every other element in your list for every tuple you consider, which is really inefficient (the code would take N**2 steps for a list of N tuples).

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