Python 类型错误:';在<;字符串>';需要字符串作为左操作数,而不是列表(列表理解)
我正在尝试检查列表中的单词是否显示在我的列中。如果单词显示在列中,则转换为1或0。但是我得到了Python 类型错误:';在<;字符串>';需要字符串作为左操作数,而不是列表(列表理解),python,string,python-3.x,list-comprehension,typeerror,Python,String,Python 3.x,List Comprehension,Typeerror,我正在尝试检查列表中的单词是否显示在我的列中。如果单词显示在列中,则转换为1或0。但是我得到了TypeError:“in”需要字符串作为左操作数,而不是listerror top_words_list = ['great', 'love', 'good', 'story', 'loved', 'excellent', 'series', 'best', 'one'] [1 if re.search(top_words_lis
TypeError:“in”需要字符串作为左操作数,而不是list
error
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 if any(word in i for word in top_words_list) else 0 for i in amazon['reviewer_summary']]
re.search()
返回所有匹配项的列表。因此,当您在i
中执行if re.search()时,您正在检查if in
,这就是它引发类型错误的原因
同样的一个小演示:
>>> 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
>chars\u to\u check=['a','b','c']
>>>句子='这是一个句子'
>>>chars_to_签入句
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“in”需要字符串作为左操作数,而不是列表
>>>
>>>任何(c在句子中表示c在字符到检查中)
真的