繁体   English   中英

Python-3.x:使用以下代码时出现错误,因为“对象没有属性'split''”

[英]Python-3.x: while using the following code i got an error as “object has no attribute 'split ”'

n = int(input())
arr = [int(x) for x in input.split()]

这是我使用的代码。 我想从用户那里获取输入列表,但由于出现错误

    arr = [int(x) for x in input.split()]
    AttributeError: 'builtin_function_or_method' object has no attribute 'split'

您正在对内置函数input调用split。 您应该在n变量上调用它。 所以应该看起来像这样

n = int(input()) 
arr = [int(x) for x in n.split()] # Still wrong

但是我还是要引用int但是没有split属性。 因此,请确保它是String类型。

因此,在处理该值之前,请勿尝试将输入转换为int

您试图拆分输入函数本身,而不是结果。 您需要分割返回的字符串,例如此input().split() 请注意,这不会做任何事情,因为split没有参数。 它只会返回一个列表,其中用户输入是唯一的参数。 如果要将输入字符串分成其字符,则可以简单地使用list(input())

我相信这就是您要的目的,将输入内容转换为列表,并为列表中的项目输入整数

  l = [int(i) for i in list(input('Enter number: '))]
 Enter number: 101 [1, 0, 1] 

正如Vineeth所说,您正在尝试在输入时调用split。 另外,您不能拆分整数,因为split是只能在字符串上使用的方法,因此不应将n强制转换为整数。

n = str(input())
arr = [int(x) for x in n.split()]

暂无
暂无

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

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