代码之家  ›  专栏  ›  技术社区  ›  Jake Park

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

  •  1
  • Jake Park  · 技术社区  · 6 年前

    我正在尝试检查列表中的单词是否显示在我的列中如果单词显示在列中,则转换为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 回复  |  直到 6 年前
        1
  •  2
  •   Keyur Potdar    6 年前

    您正在寻找

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

    re.search() 返回a 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