代码之家  ›  专栏  ›  技术社区  ›  Josh Friedlander

用列表理解替换字符串时出现类型错误

  •  0
  • Josh Friedlander  · 技术社区  · 7 年前

    ['found' if 'some_string' in word else word for word in wordlist]
    

    但它又回来了

        TypeError                                 
    Traceback (most recent call last)
        <ipython-input-108-990cad51d935> in <module>()
        ----> 1 [word  for word in wordlist if 'some_string' in word ]
    
        <ipython-input-108-990cad51d935> in <listcomp>(.0)
        ----> 1 [word  for word in wordlist if 'some_string' in word ]
    
        TypeError: argument of type 'NoneType' is not iterable
    

    相比之下,此代码的运行完全符合预期:

    for word in wordlist:
        if 'some_string' in word:
            print ('found')
        else:
            print(word)
    

    进一步的上下文:wordlist是Jupyter笔记本中Pandas数据框的一列中的值。

    wordlist = list(df.sender.values)
    type(wordlist)
     list
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   DrM    7 年前

    只需使用“str()”启用与从列表中恢复的值的比较,就可以解决这个问题。

    下面是一个例子来说明这一点:

    wordlist = ['some_string', 'sometext', 'some_string', 'randomtext', None]
    ['found' if 'some_string' in str(word) else word for word in wordlist]
    

    输出是

    ['found', 'sometext', 'found', 'randomtext', None]
    

        2
  •  1
  •   Ilia Gilmijarow    7 年前

    你有 None 单词列表中的值。 一旦遇到第一个错误,它就会抛出错误。 Python无法遍历 类型,但它需要开始迭代以确定变量中是否包含字符串。

        3
  •  1
  •   Sruthi    7 年前

    output = ['found' if (word and 'some_string' in word) else word for word in wordlist]
    

    关键是 if word None 数据帧中的元素,这会影响迭代。 我认为这与unicode元素无关