Python-TypeError:“ int”对象不可迭代

Python-TypeError:“ int”对象不可迭代,第1张

Python-TypeError:“ int”对象不可迭代

您的问题是与此行:

number4 = list(cow[n])

它尝试采用

cow[n]
,它返回一个整数,并使其成为列表。如下所示,这不起作用:

>>> a = 1>>> list(a)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'int' object is not iterable>>>

也许你的意思是把

cow[n]
里面 的列表:

number4 = [cow[n]]

请参见下面的演示:

>>> a = 1>>> [a][1]>>>

另外,我想解决两件事:

  1. 您的while陈述
    :
    结尾缺少。
  2. input
    那样使用是非常危险的,因为它将输入作为真实的Python代码进行评估。最好使用
    raw_input
    ,然后使用将其转换为整数
    int

要拆分数字,然后根据需要添加它们,我首先将数字设置为字符串。然后,由于字符串是可迭代的,因此可以使用

sum

>>> a = 137>>> a = str(a)>>> # This way is more common and preferred>>> sum(int(x) for x in a)11>>> # But this also works>>> sum(map(int, a))11>>>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5673327.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存