【问题标题】:Python list comprehension even string length or notPython列表理解甚至字符串长度与否
【发布时间】:2018-09-29 05:54:06
【问题描述】:

我正在尝试使用列表理解打印“偶数”或不打印,但出现错误。

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

这背后的原因是什么?

【问题讨论】:

  • 一个字符串怎么会是偶数?您是否要测试 长度
  • 谢谢!!!现在感觉自己很傻。是的,想测试他们的长度
  • 您正在尝试查看字符串是否为偶数?我很难看到你要去哪里。你想看看字符数是不是偶数??

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


【解决方案1】:

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

>>> 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】:

    % 运算符与字符串一起用作左侧参数时,用于 printf 样式格式。如果你想测试你的字符串的长度,你需要用len从字符串转换成长度,例如

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

    【讨论】:

      【解决方案3】:

      其他答案解释了为什么您的语法不正确。

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

      消除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']
      

      【讨论】:

        猜你喜欢
        • 2019-12-23
        • 1970-01-01
        • 2019-07-07
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-02
        • 1970-01-01
        相关资源
        最近更新 更多