简体   繁体   中英

How to append an array of space-separated integers input in an array in python?

I want to append user input of space-separated integers, as integers not array, into a formed array. Is there a way to do this?

Here is a pseudo-code:

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

I want it to be time-efficient, this is what I tried:

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

Is there a more efficient / faster way?

Expected output:

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

You can do so:

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

You can also do it as:

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

You can do so by joining two lists using '+' operator -

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

Output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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