2

我需要从用户那里拆分 raw_input(由 10 个整数组成),这样我才能找到最大的奇数。如果字符串中没有赔率,则最终输出应该是最大的奇数或“无”。这段代码给了我一个 TypeError: not all arguments 在字符串格式错误期间转换。我正在使用 Python 2.7。

这是我所拥有的:

def uiLargestOddofTen():
    userInput = raw_input("Please enter ten integers:")
    oddList = []
    x = userInput.split()
    n = 10
    for element in x:
        y = int(element)
        while n > 0:
            if element % 2 != 0:
                oddList.append(y)
                n = n - 1
    return max(oddList)

谢谢你的帮助!!

4

4 回答 4

3

列表理解怎么样:

if len(x) == 10:
  oddList = [int(a) for a in x if int(a) % 2]
    if oddList:
      return max(oddList)

假设 x 需要 10 个值长;假设您不需要 else 语句。

您不需要检查int(a) % 2 != 0,因为如果它为零,它无论如何都会返回 false 。

于 2013-09-05T18:46:29.643 回答
2

The TypeError comes from your using the strings that come from userInput.split() without explicitly converting them to ints before you do math on them. Note that the other answers fix this by surrounding their references to elements in that list with int() which forces a conversion of the input strings of digits to integers.

Edit: This line:

if element % 2 != 0:

should become:

if y % 2 != 0:

Then your code will work, although some of the other answers here offer much more concise alternatives.

于 2013-09-05T18:49:09.640 回答
2

You could try something like this:

def solve(strs):
    inp = strs.split()
    #convert items to `int` and get a filtered list of just odd numbers
    odds = [x for x in (int(item) for item in inp) if x%2]
    #if odds is not empty use `max` on it else return None
    return max(odds) if odds else None
... 
>>> print solve('2 4 6 8 11 9 111')
111
>>> print solve('2 4 6 8')
None

itertools.imap version of the above code:

from itertools import imap
def solve(strs):
    inp = imap(int, strs.split())
    odds = [x for x in inp if x%2]
    return max(odds) if odds else None
... 
>>> print solve('2 4 6 8 11 9 111')
111
>>> print solve('2 4 6 8')
None

In , max() now accepts a default value that is returned when the iterable passed to it is empty. So above code can be changed to:

def solve(strs):
    #except `strs.split()` no other list is required here.
    inp = map(int, strs.split())
    return max((x for x in inp if x%2), default=None)
于 2013-09-05T18:51:07.863 回答
1
max(filter(lambda x: int(x) & 1, raw_input().split()))

如果没有奇数,它会抛出一个异常,所以你可以捕获它然后返回 None。

完整代码示例:

try:
    res = max(filter(lambda x: int(x) & 1, raw_input().split()))
except ValueError:
    res = None

print res
于 2013-09-05T18:52:34.533 回答