TypeError:int()参数必须是字符串或数字,而不是'list'

时间:2013-03-25 20:59:58

标签: python while-loop iteration typeerror

#iterative program to find the highest odd number
m = sorted([a, b, c, d, e, f, g, h, j, k])
n = max(m)
n = int(n)
count = 10
while n%2==0:
    m=[m[:-1]]
    n = max(m)
    n = int(n)
    count =-1
if count==0:
    print 'There are no odd numbers'
else:
    print str(n), 'is the largest odd number'

我输入包含奇数的变量,它给出了正确答案,但是当我输入所有偶数以满足'count==0'条件时,会发生以下错误:

  

TypeError:int()参数必须是字符串或数字,而不是'list'

我无法理解为什么在输入奇数时不会发生此错误。

3 个答案:

答案 0 :(得分:3)

如果打印出循环中的m,这就变得非常明显了。或者您可能希望使用interactive visualizer或仅调试器来测试它。

假设您的值为2, 4, 6, 8, 10, 12, 14, 16, 18, 20。排序后,你得到了:

m = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
n = max(m) = 20
n = int(n) = 20

这个max没用,因为排序的定义必须是列表中的最后一个值(而你似乎依赖于循环中的那个)。

并且int具有误导性 - 即使数字是字符串而不是数字,它看起来就像你的代码会工作一样,但它实际上不会,因为sorted(和{{1 }})会将max视为小于'10',依此类推。

但这些都不是你的大问题。因为你的第一个'2'是偶数,你将进入循环,循环中的第一件事是:

n

......将会这样做:

m=[m[:-1]]

所以,接下来的两行是这样做的:

m = [[2, 4, 6, 8, 10, 12, 14, 16, 18]]

繁荣,这是你的例外。

如果您想将n = [2, 4, 6, 8, 10, 12, 14, 16, 18] # the max of a 1-element list is that element n = int([2, 4, 6, 8, 10, 12, 14, 16, 18]) 设置为m的最后一个元素,请执行m。在它周围抛出那些额外括号将m = m[:-1]设置为由一个元素组成的m,该元素本身是由list的最后一个元素组成的列表。

请注意,尽管您在描述中说了“我输入包含奇数的变量,但它给出了正确答案”,但事实并非如此。只有当你的最大值是奇数时它才有效,所以你从不首先进入循环。

修复此问题后,您的代码实际上仍然无法解决,但希望您现在知道如何自行调试。


与此同时,解决这个问题的pythonic方法是尝试将您的高级英语描述直接翻译成高级Python。我们如何找到m中最高的奇数?

首先得到m中的奇数:

m

(如果您创建odds = (n for n in m if n % 2) 函数,这可能更具可读性 - 如果您,您可能更喜欢odd到生成器表达式。)

然后,获得最大值:

filter

当然你需要处理没有赔率的情况。您可以通过选中max_odd = max(odds) 来完成此操作。但是在python中,通常要求宽恕比允许更好,所以,这是你的整个程序:

if odd:

答案 1 :(得分:0)

m=[m[::-1]]发生错误,正如@abarnert指出的那样。

这是一种在列表中找到最大奇数的简单方法:

m = sorted([int(n) for n in [a, b, c, d, e, f, g, h, j, k] if n%2==1])
# this makes a list of all ODD integers (converts them from strings)
if len(m) != 0:
    print str(max(m)), 'is the largest odd number'
else:
    print 'No odd integers inputted'

进一步简化为:

m = sorted([int(n) for n in [a, b, c, d, e, f, g, h, j, k] if n%2==1])
print (str(max(m)), 'is the largest odd number') if len(m)!=0 else 'No odd integers inputted'

答案 2 :(得分:-3)

当你只有偶数时,你的while循环会在你完全减少m时产生这个错误。在这种情况下,max(m)会返回None,这不能是int的参数。要解决此问题,您需要将while循环条件更改为更正确的内容。

然而,这并不是大多数人认为的“pythonic”。理想情况下,您可以使用更像for n in m[::-1]的循环,它以相反的顺序遍历m(或使用reverse=True的{​​{1}}参数,只使用sorted。)