这段代码有什么问题? (我试图让用户输入10个整数,然后返回最大的奇数,如果没有赔率则返回一个声明如此说明)
numbers = raw_input('Enter 10 integers separated by comma ')
numbers = [numbers.split(',')]
odds = [x for x in numbers if x%2==1]
if not odds:
print "no odd number was entered"
else:
print max(odds)
答案 0 :(得分:3)
我猜numbers
是str
个实例的列表。试试numbers = [int(n) for n in numbers.split(',')]
。
答案 1 :(得分:1)
你需要做两件事:
删除此行上的方括号:
numbers = [numbers.split(',')]
否则,str.split
返回的列表将放在另一个列表中。
将str.split
返回的字符串列表转换为整数列表。这可以通过map
和int
完成:
numbers = map(int, numbers.split(','))
否则,下一行中的%
将被解释为字符串格式,这将引发错误:
Traceback (most recent call last):
File ".\t.py", line 3, in <module>
odds = [x for x in numbers if x%2==1]
TypeError: not all arguments converted during string formatting
以下是您脚本的固定版本:
numbers = raw_input('Enter 10 integers separated by comma ')
numbers = map(int, numbers.split(','))
odds = [x for x in numbers if x%2==1]
# The Python standard for indentation is 4 spaces
if not odds:
print "no odd number was entered"
else:
print max(odds)
演示:
>>> numbers = raw_input('Enter 10 integers separated by comma ')
Enter 10 integers separated by comma 1,2,3,4,5,6,7,8,9,10
>>> numbers = map(int, numbers.split(','))
>>> odds = [x for x in numbers if x%2==1]
>>> if not odds:
... print "no odd number was entered"
... else:
... print max(odds)
...
9
>>>