简体   繁体   中英

Remove tuple from list similar to tuple in another list

i am new to python and to programming in general. I have a problem with removing tuples from a list that have similarity with tuples from another list.

List1=[(1,2,3,4,5),(1,3,6,7,8)]

List2=[(1,2,3,7,9),(1,4,8,9,10),(1,3,8,9,10)]

I want to remove tuples from List2 that have 3 similar elements in tuples of List1.

Outputlist=[(1,4,8,9,10)]

What is the most efficient way to do it? Thanks in advance.

You can do it using a for loop, and each time your criteria is met, delete that element from List2 and go to the next one:

List1=[(1,2,3,4,5),(1,3,6,7,8)]
List2=[(1,2,3,7,9),(1,4,8,9,10),(1,3,8,9,10)]

for index, elem2 in enumerate(List2):
    for elem1 in List1:
        # Find common items using set intersection.
        commonItems = len(set(elem2).intersection(set(elem1)))
        if commonItems == 3:
            del List2[index]
            break

print(List2)

This will return:

[(1, 4, 8, 9, 10)]

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