TypeError:'in <string>'需要字符串作为左操作数,而不是列表(列表理解)

时间:2018-03-30 13:33:16

标签: python string python-3.x list-comprehension typeerror

我正在尝试检查列表中的单词是否显示在我的列中,如果单词显示在列中,则转换为1,否则为0.但是我得到TypeError: 'in <string>' requires string as left operand, not list错误。

top_words_list = ['great', 'love', 'good',
                  'story', 'loved', 'excellent',
                  'series', 'best', 'one']
[1 if re.search(top_words_list) in i else 0 for i in amazon['reviewer_summary']]

1 个答案:

答案 0 :(得分:2)

您正在寻找

[1 if any(word in i for word in top_words_list) else 0 for i in amazon['reviewer_summary']]

re.search()返回所有匹配的list。因此,当您执行if re.search() in i时,您正在检查if <list> in <string>这就是为什么它会提升TypeError

同样的小型演示:

>>> chars_to_check = ['a', 'b', 'c']
>>> sentence = 'this is a sentence'
>>> chars_to_check in sentence
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> any(c in sentence for c in chars_to_check)
True
相关问题