在Python中输入数组可以通过以下几种方法:
方法一:使用`list()`函数和`input()`函数
1. 使用`input()`函数获取用户输入的字符串。
2. 使用`split()`函数以逗号或其他分隔符将输入的字符串拆分成列表。
3. 使用`list()`函数将列表转换为数组。
示例代码:
获取用户输入并以逗号分隔
user_input = input("Enter the elements of the array, separated by commas: ")
将输入的字符串拆分成列表
input_list = user_input.split(',')
将列表转换为数组
my_array = list(input_list)
print(my_array)
方法二:使用`numpy.array()`函数
1. 使用`input()`函数获取用户输入的字符串。
2. 使用`split()`函数以空格或其他分隔符将输入的字符串拆分成列表。
3. 使用`list()`函数将列表转换成列表。
4. 使用`numpy.array()`函数将列表转换成NumPy数组。
示例代码:
import numpy as np
获取用户输入并以空格分隔
user_input = input("Enter the elements of the array, separated by spaces: ")
将输入的字符串拆分成列表
input_list = user_input.split()
将列表转换成列表
input_list = list(input_list)
将列表转换成NumPy数组
my_array = np.array(input_list)
print(my_array)
输入一维数组
获取用户输入并以空格分隔
user_input = input("Enter the elements of the array, separated by spaces: ")
将输入的字符串拆分成列表
input_list = user_input.split()
将列表转换为数组
my_array = [int(n) for n in input_list]
print(my_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] = list(map(int, input("Enter row {} elements separated by spaces: ".format(i+1)).split()))
print(line)
以上是Python中输入数组的一些常见方法。您可以根据需要选择适合您需求的方法