Home > database >  compare two lists with multiple attributes regarding the first attribute of each entry
compare two lists with multiple attributes regarding the first attribute of each entry

Time:10-27

I'm struggeling at an implementation in python for the following probelm:

I have two lists which look similar to the once below:

list1 = [("aa",2),("bb",1),("cc",5),("dd",3),("ee",7)]
list2 = [("bb",3),("dd",1),("cc",2)]

Regarding the first attribute of the lists - the String, the second list, list2, consists out of a selection of the Strings available in the first list, list1. Regarding the second attribute of the lists - the Integer, values can vary.

What I need for my problem is an algorithm in python, which compares the two lists, list1 and list2 regarding "the String attribute" and removes all entries from list1 that don't have a String in common with list2.

As a result there should be list1 only with the same String attributes as in list2.

It is also important that the "new" list1 still consists out of the tuples from the beginning, so the Integer attribute is from the former list1.

Therefore the result should be:

list1 = [("aa",2),("cc",5),("dd",3)]

Looking forward to any help. Thanks in advance.

I already tried several approaches with also converting into sets, but couldn't get something working yet.

CodePudding user response:

Assuming the string values in list2 are unique, you could make a set of them and then use a list comprehension over list1 to generate the required output, checking whether the string element is contained in the set:

list1 = [("aa",2),("bb",1),("cc",5),("dd",3),("ee",7)]
list2 = [("bb",3),("dd",1),("cc",2)]
strings = set(t[0] for t in list2)
result = [t for t in list1 if t[0] in strings]
# [('bb', 1), ('cc', 5), ('dd', 3)]
  • Related