在Python中,手动输入数组可以通过以下几种方法实现:
方法一:使用`list()`函数和`input()`函数
获取用户输入,以逗号分隔
user_input = input("Enter the elements of the array, separated by commas: ")
使用split()函数以逗号为分隔符将输入字符串拆分为一个列表
input_list = user_input.split(',')
使用list()函数将列表转换为数组
my_array = list(input_list)
print(my_array)
方法二:使用`numpy.array()`函数
import numpy as np
获取用户输入,以空格分隔
user_input = input("Enter the elements of the array, separated by spaces: ")
使用split()函数以空格为分隔符将输入字符串拆分为一个列表
input_list = user_input.split()
使用list()函数将列表转换为一个普通的Python列表
input_list = list(input_list)
使用numpy.array()函数将列表转换为NumPy数组
my_array = np.array(input_list)
print(my_array)
方法三:输入一维数组
获取用户输入的一维数组,每个数之间用空格隔开
user_input = input("Enter the elements of the array, separated by spaces: ")
使用split()函数以空格为分隔符将输入字符串拆分为一个列表
input_list = user_input.split()
将输入的每个数转换为整数,并创建一个一维数组
num_array = [int(n) for n in input_list]
print(num_array)
方法四:输入二维数组
获取用户输入的二维数组的行数和列数
n = int(input("Enter the number of rows and columns for the 2D array: "))
初始化一个二维数组
line = [*n]*n
循环输入二维数组的每一行
for i in range(n):
获取当前行的输入,以空格隔开
line[i] = input("Enter the elements of row {} separated by spaces: ".format(i+1)).split()
将二维数组中的每一行转换为整数
for i in range(n):
line[i] = [int(j) for j in line[i]]
print(line)
以上方法可以帮助你在Python中手动输入一维和二维数组。请根据你的需求选择合适的方法