Markus
Markus

Reputation: 71

Compare two lists for content

I have the given the following two lists:

list1 = ['', '', 'void KL15 ein', '{', '}', '', 'void Motor ein', '{', '}', '']
and
list2 = ['KL15 ein', 'Motor ein']

Now I want to find out if the a value from the second list 'KL15 ein' is also in the first list (as a void function). Do I need to extract the value 'KL15 ein' from both lists to compare it or is there another way to do it without extracting (via splitting and access the list) the values? Edit: I noticed that I need variables (can't use 'KL15 ein' as a string), e.g: if the value from list1 is also listed in list 2

Upvotes: 1

Views: 86

Answers (2)

tobias_k
tobias_k

Reputation: 82929

First, get the set of void function names from the first list by checking which strings start with "void " and then stripping away that bit. Then, you can use a simple list comprehension, all expression or for loop to check which of the elements in the second list are in that set.

lst1 = ['', '', 'void KL15 ein', '{', '}', '', 'void Motor ein', '{', '}', '']
lst2 = ['KL15 ein', 'Motor ein']                                        
void_funs = {s[5:] for s in lst1 if s.startswith("void ")}              
res = [s in void_funs for s in lst2]                                          
# [True, True]

Or as a loop with a condition:

for s in lst2:
    if s in void_funs:
        # do something

Upvotes: 1

I think you can use the issubset() or all() function.

issubset()

if(set(subset_list).issubset(set(large_list))):
    flag = 1
 
# printing result
if (flag):
    print("Yes, list is subset of other.")
else:
    print("No, list is not subset of other.")

or all() function

if(all(x in test_list for x in sub_list)):
    flag = 1
 
# printing result
if (flag):
    print("Yes, list is subset of other.")
else:
    print("No, list is not subset of other.")

Upvotes: 1

Related Questions