![](/img/trans.png)
[英]how can I get the index of the item in a list that contains the string being search (within the list) in python
[英]Python - Search a list item that contains a string (match case)
我需要搜索列表中的任何項目是否包含特定字符串。 目前,我使用以下代碼:
mylist = ['Hometown City Heights', 'Height 6'', 'First name Mike']
item = [s for s in mylist if "First name" in s]
print item[0]
>> First name Mike
問題是,如果我嘗試搜索“ Height
,則會得到以下信息:
mylist = ['Hometown City Heights', 'Height 6'', 'First name Mike']
item = [s for s in mylist if "Height" in s]
print item[0]
>> Hometown City Heights
我只需匹配Height
包括在Height 6'
的元素,所以該項目[0]將是我所需要的一個。 最好的方法是什么?
您可以拆分項目,然后檢查:
item = [s for s in mylist if "Height" in s.split()]
演示:
>>> mylist = ['Hometown City Heights', "Height 6'"]
>>> [s for s in mylist if "Height" in s.split()]
["Height 6'"]
>>>
作為更一般的方法,您可以使用正則表達式搜索模式:
import re
[s for s in mylist if re.search(r'\b{}\b'.format(pattern),s)]
演示:
>>> pattern='First name'
>>> [s for s in mylist if re.search(r'\b{}\b'.format(pattern),s)]
['First name Mike']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.