【发布时间】:2018-01-02 10:43:02
【问题描述】:
我有一个清单如下。
mylist = ['test copy', 'test project', 'test', 'project']
我想看看我的句子是否包含上述mylistelements,并从第一个匹配中拆分句子并获取它的第一部分。
例如:
mystring1 = 'it was a nice test project and I enjoyed it a lot'
输出应该是:it was a nice
mystring2 = 'the example test was difficult'
输出应该是:the example
我目前的代码如下。
for sentence in L:
if mylist in sentence:
splits = sentence.split(mylist)
sentence= splits[0]
但是,我收到一条错误消息,提示 TypeError: 'in <string>' requires string as left operand, not list。有没有办法解决这个问题?
【问题讨论】:
-
这里的L是什么?
-
您在寻找
if sentence in mylist?.. -
您可能在 mylist 中而不是句子中循环,您可以根据列表中的每个单词拆分整个句子。您还将结果分配给新变量。
-
@Sayse:我认为这句话是一个示例输入。