Python 3.30 TypeError:“int”类型的对象没有 len()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15182804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 3.30 TypeError: object of type 'int' has no len()
提问by user2128205
Here's the error I get for i in range(len(n)):
这是我得到的错误for i in range(len(n)):
TypeError: object of type 'int' has no len()
I have seen other posts on here but haven't found the solution yet.
I'm confused. Please comment if you know what's going on here.
我在这里看到了其他帖子,但还没有找到解决方案。
我糊涂了。如果您知道这里发生了什么,请发表评论。
Here's my code:
这是我的代码:
#ch6.ex11.py
def squareEach(x):
sqrt = x*x
return sqrt
def main():
n = []
n = eval(input("Enter a list of numbers to be squared seperated by comma:\n"))
i = 1
sqrtn = ()
for i in range(len(n)):
sqrtn = squareEach(n)
++i
print("Here's your results: ",sqrtn)
main()
回答by nneonneo
nis an integer. You want
n是一个整数。你要
for i in range(n):
回答by Ankur Ankan
This is what I guess you are trying to do:
这就是我猜你正在尝试做的事情:
def squareEach(x):
sqrt = x*x
return sqrt
def main():
n = list(map(int, input("Enter a list of numbers to be squared separaded by a comma").split(',')))
sqrtn = []
for i in range(len(n)):
sqrtn.append(squareEach(n[i]))
print("Here's your results: ",sqrtn)
main()
or you can use the for loop as:
或者您可以将 for 循环用作:
for i in n:
sqrtn.append(squareEach(i))
or to square each element you can do:
或者对每个元素进行平方,您可以执行以下操作:
sqrtn = [x**2 for x in n]
回答by pradyunsg
It seems you might want to do this:
看来你可能想要这样做:
def squareEach(n):
squares = []
for i in n:
squares.append(i*i)
return squares
def main():
msg = "Enter a list of numbers to be squared seperated by comma:\n"
n = list(eval(input(msg)))
sqrtn = squareEach(n)
print("Here's your results: ",sqrtn)
main()
Well, your code has a few problems:
好吧,你的代码有几个问题:
- You should change your into a list, as you are iterating through it.
- In Python's for loop, you don't need a loop counter (unless it is of some use to the program, which it is not in this case)
i++is not valid in Python. The Python equivalent to it isi += 1.
- 您应该将您的更改为一个列表,因为您正在遍历它。
- 在 Python 的 for 循环中,您不需要循环计数器(除非它对程序有用,在这种情况下不是这样)
i++在 Python 中无效。与它等效的 Python 是i += 1.
Also, Python executes all the lines of code in a script, so you don't need a main()function in every Python program, but there are some cases when you might want to use it.
此外,Python 执行脚本中的所有代码行,因此您不需要main()在每个 Python 程序中都有一个函数,但在某些情况下您可能想要使用它。
Something else you can do:
你可以做的其他事情:
def main():
msg = "Enter a list of numbers to be squared seperated by comma:\n"
n = list(eval(input(msg)))
squares = [i**2 for i in n] # list comprehension
main()

