AttributeError:“tuple”对象没有结果为input()的属性“split”?

2024-05-17 19:58:18 发布

您现在位置:Python中文网/ 问答频道 /正文

(这是家庭作业)以下是我所拥有的:

L1 = list(map(int, input().split(",")))

我遇到了

  File "lab3.py", line 23, in <module>
    L1 = list(map(int, input().split(",")))
AttributeError: 'tuple' object has no attribute 'split'

是什么导致了这个错误?

我使用1, 2, 3, 4作为输入


Tags: inpyl1mapinputlinelistfile
1条回答
网友
1楼 · 发布于 2024-05-17 19:58:18

您需要使用raw_input,而不是input

raw_input().split(",")

在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'

如果你想知道它实际上是一个元组:

>>> v = input()
1,3,9
>>> v[0]
1
>>> v[1]
3
>>> v[2]
9
>>> v
(1, 3, 9)

最后,比起listmap你最好能理解列表

L1 = [int(i) for i in raw_input().split(',')]

相关问题 更多 >