簡體   English   中英

如何在 python 的數組中輸入一個空格分隔的整數數組 append?

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

我想將 append 用戶輸入的空格分隔的整數,作為整數而不是數組,放入一個形成的數組中。 有沒有辦法做到這一點?

這是一個偽代碼:

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)

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

預期 output:

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

你可以這樣做:

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

Output

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM