Home > Mobile >  Is there a function to compare items in a list?
Is there a function to compare items in a list?

Time:12-22

is there a way for me to compare two different lists and only take out what is similar? Example:

list1 = [(JOHN,BLUE,BANANA),(JOHN,BLUE, APPLE),(MARY,PURPLE,GRAPE),(BEN,GREEN,WATERMELON)
list2 = [(JOHN,BLUE),(MARY,PURPLE),(TOMMY,PINK)]
OUTPUT:
[(JOHN, BLUE, BANANA),(JOHN, BLUE, APPLE),(MARY, PURPLE, GRAPE)]

CodePudding user response:

Just check item[:2] from list1 in list2

list1 = [
    ('JOHN', 'BLUE',   'BANANA'),
    ('JOHN', 'BLUE',   'APPLE'),
    ('MARY', 'PURPLE', 'GRAPE'),
    ('BEN',  'GREEN',  'WATERMELON'),
]
list2 = [
    ('JOHN',  'BLUE'),
    ('MARY',  'PURPLE'),
    ('TOMMY', 'PINK')]

print([item for item in list1 if item[:2] in list2])
[('JOHN', 'BLUE', 'BANANA'), ('JOHN', 'BLUE', 'APPLE'), ('MARY', 'PURPLE', 'GRAPE')]

CodePudding user response:

You could try the following rudimental one:

list1 = [("JOHN","BLUE","BANANA"),("JOHN","BLUE", "APPLE"),("MARY","PURPLE","GRAPE"),("BEN","GREEN","WATERMELON")]
list2 = [("JOHN","BLUE"),("MARY","PURPLE"),("TOMMY","PINK")]

tmp = set()
for i in list1:
    for j in list2:
        if len(set(i)&set(j)) > 0:
            tmp.add(i)
print tmp

Result:

set([('MARY', 'PURPLE', 'GRAPE'), ('JOHN', 'BLUE', 'BANANA'), ('JOHN', 'BLUE', 'APPLE')])

CodePudding user response:

def common_member(a, b):
    a_set = set(a)
    b_set = set(b)
 
    if (a_set & b_set):
        print(a_set & b_set)
    else:
        print("No common elements")
a = [JOHN,BLUE,BANANA),(JOHN,BLUE, APPLE),(MARY,PURPLE,GRAPE),(BEN,GREEN,WATERMELON]
b = [(JOHN,BLUE),(MARY,PURPLE),(TOMMY,PINK)]
common_member(a, b)
  • Related