我是python的新手,我在下面的代码中遇到了简单的问题 代码应该给出结果' x100'虽然它是' x10'和' x100'。如何获得预期的结果。
test_list=['x10','x50','x100']
text='this text has x100 only'
for i in test_list:
if text.find(i)!=-1:
print "found "+i
>>>
found x10
found x100
>>>
答案 0 :(得分:1)
更简单的方法是
test_list=['x10','x50','x100']
text='this text has x100 only'
for i in test_list:
if i in text.split():
print "found "+i
要检测
test_list=['x10','x50','x100']
test_list= sorted(test_list,key = lambda x: len(x), reverse = True)
text='this text has x100n only'
import re
a = re.search("|".join(test_list),text)
if a:
print "Found",a.group()
答案 1 :(得分:1)
您可以使用.split()
查找它是否在单词列表中:
>>> test_list=['x10','x50','x100']
>>> text='this text has x100 only'
>>> for i in test_list:
... if i in text.split():
... print "found",i
...
found x100
答案 2 :(得分:0)
您可以使用此简单列表解析来查找所有实例。额外奖励:它只计算一次拆分。
def f(s, lst):
return [item for item in lst if item in s.split()]
测试它:
>>> test_list=['x10','x50','x100']
>>> text='this text has x100 only'
>>> f(text, test_list)
['x100']