我正在尝试使用列表理解来打印“偶数”或不打印“偶数”,但出现错误。
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
背后的原因是什么?
您%
在字符串上使用运算符:
>>> 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 字符串格式。这需要一个%
-style 占位符来格式化右侧的值。如果左侧的字符串中没有占位符,则会出现您看到的错误。
如果要测试字符串的长度是否为偶数,则需要使用该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']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句