Python列表理解甚至字符串长度与否

Emr*_*boz 0 python string list-comprehension list python-3.x

我试图打印"偶数"或不打印列表理解,但我得到一个错误.

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
Run Code Online (Sandbox Code Playgroud)

它背后的原因是什么?

Mar*_*ers 5

%在字符串上使用运算符:

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

%字符串上使用时,您没有获得模数,而是使用printf-style字符串格式.这需要一个%样式占位符来将右侧的值格式化为.如果左侧的字符串中没有占位符,则会出现您看到的错误.

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

myList3 = ['even' if len(x) % 2 == 0 else 'nope' for x in myNames]
Run Code Online (Sandbox Code Playgroud)

演示:

>>> myNames = ['A','BB','CCC','DDDD']
>>> ['even' if len(x) % 2 == 0 else 'nope' for x in myNames]
['nope', 'even', 'nope', 'even']
Run Code Online (Sandbox Code Playgroud)