我对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
>>> 发布于 2015-01-14 13:44:58
更简单的方法是
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()发布于 2015-01-14 13:45:14
您可以使用.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发布于 2015-01-14 14:04:52
您可以使用这个简单的列表理解来查找所有实例。奖励:它只计算一次分割。
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']https://stackoverflow.com/questions/27944387
复制相似问题