提问者:小点点

如何在Python中追加数组中输入的空格分隔的整数数组?


我想将用户输入的空格分隔的整数,作为整数而不是数组,追加到一个已形成的数组中。 有办法做到这一点吗?

下面是一个伪代码:

a=[1,2,3,4]
a.append(int(input().split())
print(a)

我想让它省时,这就是我试过的:

a=[1,2,3,4]
b=list(map(int, input().rstrip().split()))
a.extend(b)
print(a)

有没有更有效/更快的方法?

预期产出:

[1, 2, 3, 4, 5, 6, 7, 8]
# When input is '5 6 7 8'

共3个答案

匿名用户

您可以这样做:

a=[1,2,3,4]
a.extend(map(int, input().split()))
print(a)
#[1, 2, 3, 4, 5, 6, 7, 8]

匿名用户

您也可以这样做:

a=[1,2,3,4]
b=list(map(int, input().rstrip().split()))
for i in b:
    a.append(i)
print(a)

匿名用户

您可以使用“+”运算符连接两个列表-

a = [1,2,3,4]
result = list(map(int, input().split())) + a

[5,6,7,8,1,2,3,4]