Home > Software engineering >  Compare two lists for content
Compare two lists for content

Time:09-01

I have the given the following two lists:

['', '', 'void KL15 ein', '{', '}', '', 'void Motor ein', '{', '}', '']
and
['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 the values?

CodePudding user response:

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.")

I hope it anwers

CodePudding user response:

You can do something like

#l1 is list 1, l2 is list 2
if 'void KL15 ein' in l1 and 'KL15 ein' in l2:
  #logic for if true
else:
  #logic for if not true

CodePudding user response:

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]
  • Related