代码之家  ›  专栏  ›  技术社区  ›  blockByblock

Python列表理解是否为偶数字符串长度

  •  0
  • blockByblock  · 技术社区  · 7 年前

    我试图用列表理解打印“偶数”或“非偶数”,但我遇到了一个错误。

    myNames = ['A','BB','CCC','DDDD']
    myList3 = [ 'even' if x%2==0 else 'nope' for x in myNames]
    
    Error: TypeError: not all arguments converted during string formatting
    

    这背后的原因是什么?

    3 回复  |  直到 7 年前
        1
  •  5
  •   Martijn Pieters    7 年前

    您正在使用 % 字符串上的运算符:

    >>> x = 'A'
    >>> x % 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: not all arguments converted during string formatting
    

    使用时 % 在字符串上,您没有得到模数,但使用 printf -style string formatting 相反这需要 % -右侧要格式化为的值的样式占位符。如果左侧的字符串中没有占位符,则会出现所看到的错误。

    如果您想测试 如果字符串的值为偶数,则需要使用 len() 函数获取该长度:

    myList3 = ['even' if len(x) % 2 == 0 else 'nope' for x in myNames]
    

    演示:

    >>> myNames = ['A','BB','CCC','DDDD']
    >>> ['even' if len(x) % 2 == 0 else 'nope' for x in myNames]
    ['nope', 'even', 'nope', 'even']
    
        2
  •  2
  •   jpp    7 年前

    其他答案解释了语法不正确的原因。

    如果您感兴趣,这里有一个使用字典的替代实现。

    消除 if / else 有利于词典的结构通常既高效又可读。

    myNames = ['A','BB','CCC','DDDD']
    
    mapper = {0: 'even', 1: 'nope'}
    res = [mapper[len(i) %2] for i in myNames]
    
    # ['nope', 'even', 'nope', 'even']
    
        3
  •  0
  •   ShadowRanger    7 年前

    这个 % 运算符与字符串一起用作左侧参数时,用于printf样式的格式设置。如果要测试 对于字符串,需要使用 len ,例如。

    myList3 = [ 'even' if len(x) % 2==0 else 'nope' for x in myNames]