Reputation: 21
I have two list as given below:
list1 = ['17_12_29', '17_08_04']
list2 = ['17_12_29_xyz','2017_12_29_abc', '17_08_04_mnp','17_08_04_mnp2',
'2017_08_04_def', '17_08_05_pqr']
I want to compare the two list element wise and expecting the result as given below:-
res = ['17_12_29_xyz','2017_12_29_abc', '17_08_04_mnp','17_08_04_mnp2','2017_08_04_def'].
We have different library are available to get the result, but my constraint to use python code only.
Upvotes: 0
Views: 2104
Reputation: 1521
You might wanna use in
for comparison:
res=[]
for i in list1:
for j in list2:
if i in j:
res.append(j)
Upvotes: 0
Reputation: 17166
Using list comprehension and any
res = [x for x in list2 if any(y in x for y in list1)]
print(res) # Output: ['17_12_29_xyz', '2017_12_29_abc', '17_08_04_mnp', '17_08_04_mnp2', '2017_08_04_def']
Upvotes: 2
Reputation: 41
You can check if a string exists within another string in python.
res = []
for s2 in list2:
for s1 in list1:
if s1 in s2:
res.append(s2)
Upvotes: 0
Reputation: 972
This should work:
res=[]
list1 = ['17_12_29', '17_08_04']
list2 = ['17_12_29_xyz','2017_12_29_abc', '17_08_04_mnp','17_08_04_mnp2', '2017_08_04_def', '17_08_05_pqr']
for item in list2:
for j in list1:
if j in item:
res.append(item)
break
print(res)
Upvotes: 0