如何在python中获取列表中每个数字的mod

时间:2014-03-07 02:36:06

标签: python

这段代码有什么问题? (我试图让用户输入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)

2 个答案:

答案 0 :(得分:3)

我猜numbersstr个实例的列表。试试numbers = [int(n) for n in numbers.split(',')]

答案 1 :(得分:1)

你需要做两件事:

  1. 删除此行上的方括号:

    numbers = [numbers.split(',')]
    

    否则,str.split返回的列表将放在另一个列表中。

  2. str.split返回的字符串列表转换为整数列表。这可以通过mapint完成:

    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
    

  3. 以下是您脚本的固定版本:

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