I have a 2 lists and the input looks like list1=["car", "boat", "sun", "ride"]
and list2=["car_1", "car_2", sun_3"]
. My expected output should be like output=["boat", "ride"]
.
My code snippet for your reference:
For i in list1:
If any( i in e for e in list2):
Print (i)
My code is not looping through the list1. Please Correct me what i am missing.
CodePudding user response:
You can just use List-Comprehension, then check for partial string in each item of list2 for each value in list1:
output=[v for v in list1 if not any(v in x for x in list2)]
print(output)
['boat', 'ride']
CodePudding user response:
The logic in your code will work with one modification: insert not
before any()
. To construct a list output
, replace the print()
statement with output.append(i)
where output
is initialized before the loop as output = []
.
There is an alternative approach that optimizes for a more restricted type of matching. Assuming list2
contains only strings of the form prefix '_' suffix
where prefix
and suffix
do not contain _
, and also assuming we are to keep items in list1
unless they exactly match a prefix
found in list2
, you can do it this way:
prefSet = {x.split('_')[0] for x in list2}
print( [x for x in list1 if x not in prefSet] )