简体   繁体   English

如何在 python 的数组中输入一个空格分隔的整数数组 append?

[英]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.我想将 append 用户输入的空格分隔的整数,作为整数而不是数组,放入一个形成的数组中。 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:预期 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 Output

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

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

相关问题 如何将空格分隔的数据读入 numpy 数组? - How to read space-separated data into a numpy array? 将以空格分隔的整数求和为列表中的字符串 - Sum space-separated integers as string in a list 高效读取以空格分隔的整数 - Reading space-separated integers efficiently 如何在Python中迭代空格分隔的ASCII文件 - How to iterate over space-separated ASCII file in Python 如何使用Python 3中的readlines读取由空格分隔的整数输入文件? - How to read an input file of integers separated by a space using readlines in Python 3? 在 python 中拆分 dataframe 中的空格分隔值列 - split column of space-separated values ​in dataframe in python 将浮点列表加入到 Python 中的空格分隔字符串中 - Join float list into space-separated string in Python 如何在此处分隔以空格分隔的数学运算符? - How do I split on the space-separated math operators here? 如何将 python 中的 n 个整数列表更改为普通空格分隔的整数 - how to change a list of n integers in python to normal space separated integers 如何在 pyhton numpy 数组中输入空格分隔的整数。 (就像 list(map(int,input().spli(" ")) 函数对列表所做的那样。) - How can I input space separated integers in pyhton numpy array. (Like the list(map(int,input().spli(" ")) function does for a list.)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM