python - 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?
解决方案
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
推荐阅读
- html - 我的投资组合的响应能力问题
- salesforce - Salesforce 公式逻辑
- ios - 如何在 Swift 中将 UITextField 中的数据用作数组?
- blockchain - Electrum 服务器方法:“blockchain.scripthash.subscribe”
- bash - 如何打印代理并将其添加到服务器?
- bash - 带有时间戳的批处理间隔屏幕截图
- css - CSS 在服务器上的 django site-admin 中不起作用
- laravel-5.8 - ReferenceError:未定义显示框
- spring - 本地主机 Cookie 域
- bash - 如何在单个 shell 脚本中执行更改目录并并行执行两个程序?