Python - % 不支持的操作数类型:'list' 和 'int'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18290745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - unsupported operand type(s) for %: 'list' and 'int'
提问by BubbleMonster
I've had a look at other questions on stackoverflow but they are different and don't seem to apply to this question, so here goes.
我看过有关 stackoverflow 的其他问题,但它们是不同的,似乎不适用于这个问题,所以在这里。
I've written a simple script that gives me a print out of every number between 1-49 and puts it into a list using the range function.
我编写了一个简单的脚本,它打印出 1-49 之间的每个数字,并使用 range 函数将其放入列表中。
Now I have defined a function to work out what numbers are odd and what numbers are even, here is my code:
现在我已经定义了一个函数来计算哪些数字是奇数,哪些数字是偶数,这是我的代码:
def check(number):
if number%2==0:
print "Even Numbers:",(number)
else:
print "Odd Numbers:",(number)
a = range(1,50)
print a
check(a)
I get the following error when I run the script:
运行脚本时出现以下错误:
unsupported operand type(s) for %: 'list' and 'int'
So I know that this means the % operator cannot doesn't support 'lists' or 'ints', but how can I fix it?
所以我知道这意味着 % 运算符不能不支持“列表”或“整数”,但我该如何解决?
I tried this:
我试过这个:
def check(number):
if number%2==0:
print "Even Numbers:",(number)
else:
print "Odd Numbers:",(number)
a = range(1,50)
b = str(a)
check(str(a))
But get the error:
但得到错误:
Traceback (most recent call last):
File "showEvenNumbers.py", line 12, in <module>
check(str(a))
File "showEvenNumbers.py", line 2, in check
if number%2==0:
TypeError: not all arguments converted during string formatting
So I'm a bit unsure what to do.
所以我有点不确定该怎么做。
Any help would be much appreciated.
任何帮助将非常感激。
采纳答案by Blender
a
is a list, but check
expects a single integer. You need to iterate over the list:
a
是一个列表,但check
需要一个整数。您需要遍历列表:
for item in a:
check(item)