Python AttributeError: 'tuple' 对象没有属性 'split' 与 input() 的结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33292492/
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
AttributeError: 'tuple' object has no attribute 'split' with result of input()?
提问by Chris G
(This is Homework)Here is what I have:
(这是家庭作业)这是我所拥有的:
L1 = list(map(int, input().split(",")))
I am running into
我遇到了
File "lab3.py", line 23, in <module>
L1 = list(map(int, input().split(",")))
AttributeError: 'tuple' object has no attribute 'split'
what is causing this error?
是什么导致了这个错误?
I am using 1, 2, 3, 4
as input
我1, 2, 3, 4
用作输入
采纳答案by Ryan Haining
You need to use raw_input
instead of input
你需要使用raw_input
而不是input
raw_input().split(",")
In Python 2, the input()
function will try to eval
whatever the user enters, the equivalent of eval(raw_input())
. When you input a comma separated list of values, it is evaluated as a tuple. Your code then calls split
on that tuple:
在 Python 2 中,该input()
函数将尝试eval
用户输入的任何内容,相当于eval(raw_input())
. 当您输入逗号分隔的值列表时,它会被评估为一个元组。然后您的代码调用split
该元组:
>>> input().split(',')
1,2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'split'
If you want to se that it's actually a tuple:
如果你想知道它实际上是一个元组:
>>> v = input()
1,3,9
>>> v[0]
1
>>> v[1]
3
>>> v[2]
9
>>> v
(1, 3, 9)
Finally, rather than list
and map
you'd be better off with a list comprehension
最后,而不是list
和map
你是同一个列表理解更好
L1 = [int(i) for i in raw_input().split(',')]