繁体   English   中英

TypeError:int()参数必须是字符串或数字,而不是“列表”

[英]TypeError: int() argument must be a string or a number, not 'list'

#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()参数必须是字符串或数字,而不是“列表”

我不明白为什么在输入奇数时不会出现此错误。

如果打印出循环内的m ,这将变得很明显。 或者,您可能想使用交互式可视化工具或仅调试器对其进行测试。

假设您的值是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 (和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 ,该列表本身就是由m的最后一个元素组成的列表。

请注意,尽管您在描述中说了什么,“我输入的变量包含一个奇数,但它给了我正确的答案”,但事实并非如此。 仅当您的最大值为奇数时,它才起作用,因此您永远不会进入循环。

修复此问题后,您的代码实际上仍然被破坏,但是希望现在您知道如何自己调试它。


同时,解决此问题的pythonic方法是尝试将高级英语描述直接转换为高级Python。 我们如何找到m的最高奇数?

首先获得m的奇数:

odds = (n for n in m if n % 2)

(如果您创建一个odd函数,这可能会更具可读性;并且,如果您更喜欢filter ,则可能更喜欢生成器表达式。)

然后,要获得最大值:

max_odd = max(odds)

当然,您需要处理没有赔率的情况。 您可以通过检查if odd: 但是在python中,请求宽容通常比允许许可更好,因此,这是您的整个程序:

m = [a, b, c, d, e, f, g, h, j, k]
odds = (n for n in m if n % 2)
try:
    print max(odds), 'is the largest odd number'
except ValueError:
    print 'There are no odd numbers'

如@abarnert所指出,您的错误发生在m=[m[::-1]]

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

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'

当您只有偶数时,完全填充m后,while循环会生成此错误。 在那种情况下, max(m)返回None ,它不能是int的参数。 要解决此问题,您需要将while循环条件更改为更正确的条件。

但是,这并不是大多数人认为的“ pythonic”。 理想的情况是,您应该使用一个更类似于for n in m[::-1]的循环,该循环以相反的顺序遍历m (或使用sortedreverse=True参数,仅对for n in m )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM