首页 > 解决方案 > substring of a list from another list in python

问题描述

I have a list like below

fulllist = ['item1 cost is 1', 'item2 cost is 2', 'bla bla bla', 'item3 cost is 3', 'item4 cost is 4', 'bla bla bla']

Another list with keywords

keywords = ['item1','item2','item4','item3']

I need to search fulllist with items of the keywords list and if the keyword is found as a substring from fulllist, I need that statement to be written to a new list in the same order as keywords list like:

newlist = ['item1 cost is 1', 'item2 cost is 2', 'item4 cost is 4', 'item3 cost is 3']

I tried below piece of code:

fulllist = ['item1 cost is 1', 'item2 cost is 2', 'bla bla bla', 'item3 cost is 3', 'item4 cost is 4', 'bla bla bla']
keywords = ['item1','item2','item4','item3']

newlist = [fulllistitem for fulllistitem in fulllist for i in range(0,len(keywords)) if keywords[i] in fulllistitem]

but newlist is not in the matching order of keywords list but in fullist order, like

newlist = ['item1 cost is 1', 'item2 cost is 2', 'item3 cost is 3', 'item4 cost is 4']

instead of

newlist = ['item1 cost is 1', 'item2 cost is 2', 'item4 cost is 4', 'item3 cost is 3']

how to the list as intended?

标签: pythonlist

解决方案


You are pretty close. It could be done like this, also there is no need to use range.

newlist = [item for keyword in keywords for item in fulllist if keyword in item]

Modified answer. That allows you to have 'dummy' objects in result list if there is no such object in fulllist

result = ['dummy'] * len(keywords)
for index, keyword in enumerate(keywords):
     for item in fulllist:
         if keyword in item:
            res[index] = item

推荐阅读