Python: Subset Elements In One List Based On Substring In Another List, Retain Only One Element Per Substring
I have two lists: list1 = ['abc-21-6/7', 'abc-56-9/10', 'def-89-7/3', 'hij-2-4/9', 'hij-75-1/7'] list2 = ['abc', 'hij'] I would like to subset list1 such that: 1) only those elem
Solution 1:
You can use itertools.groupby
:
import itertools
importrandomlist1= ['abc-21-6/7', 'abc-56-9/10', 'def-89-7/3', 'hij-2-4/9', 'hij-75-1/7']
list2 = ['abc', 'hij']
new_list1 = [i for i in list1 ifany(b in i for b in list2)]
new_data = [list(b) for a, b in itertools.groupby(new_list1, key=lambda x: x.split("-")[0])]
final_data = [random.choice(i) for i in new_data]
Output:
['abc-56-9/10', 'hij-75-1/7']
Solution 2:
You can use the following function:
deffind(list1, findable):
for element in list1:
if findable in element:
return element
Now we can use a list comprehension:
[find(list1, ele) for ele in list2 iffind(list1, ele) is not None]
This can be sped up without the list comprehension:
result = []
for ele in list2:
found = find(list1, ele)
if found isnotNone:
result.append(found)
Solution 3:
You can use a dictionary instead of a list, and then convert the values to a list.
list1 = ['abc-21-6/7', 'abc-56-9/10', 'def-89-7/3', 'hij-2-4/9', 'hij-75-1/7']
list2 = ['abc', 'hij']
final_list = {pref:ele for pref in list2 for ele in list1 if pref in ele}
final_list = list(final_list.values())
this would output:
>>>final_list
['abc-56-9/10', 'hij-75-1/7']
Post a Comment for "Python: Subset Elements In One List Based On Substring In Another List, Retain Only One Element Per Substring"