Reputation: 23
this is my code, with 2 lists. The script check the similar elements and put them in a new list named newlist :
list1 = ['jack sparow' , 'monika hardan', 'hamid tatan', 'california']
list2 = ['california']
newlist = []
if any(x in list1 for x in list2):
newlist.append(list2)
print(newlist)
Output : [['california']]
What i'm looking for is, even if the element in list 1 contains one word of an element in list 2, should be detected, here is an example :
list1 = ['jack sparow' , 'monika hardan', 'hamid tatan', 'california']
list2 = ['sparow']
newlist = []
if any(x in list1 for x in list2):
newlist.append(list2)
print(newlist)
Output : []
Wanted Output : [['jack sparow']]
Upvotes: 1
Views: 2038
Reputation: 2322
You can try the following:
list1 = ['jack sparow', 'monika hardan', 'hamid tatan', 'california']
list2 = ['california', 'sparow']
newlist = [[x] for x in list1 for y in list2 if y in x]
print(newlist)
which prints
[['jack sparow'], ['california']]
UPDATE
To achieve the output [['jack sparow'], [None], [None], ['california']]
, you can try the following:
def is_partially_contained_in(s, t):
for y in t:
if y in s:
return True
return False
list1 = ['jack sparow', 'monika hardan', 'hamid tatan', 'california']
list2 = ['california', 'sparow']
newlist = [[x] if is_partially_contained_in(x, list2) else [None] for x in list1]
print(newlist)
which prints
[['jack sparow'], [None], [None], ['california']]
Upvotes: 2
Reputation: 88
list1 = ['jack sparow' , 'monika hardan', 'hamid tatan', 'california']
list2 = ['california']
newlist = []
for a in list2:
for b in list1:
if a in b:
newlist.append(b)
print(newlist)
Upvotes: 2
Reputation: 6782
Try this:
if any(x in y for y in list1 for x in list2):
newlist.append(list2)
Upvotes: 1