Python创建二维数组
因一次笔试中忘记如何用python创建二维数组,遂记录下来.
成功没有捷径,一定要脚踏实地.
没有使用numpy模块,若想使用numpy模块创建二维数组请移步。
一:初始化一个元素从0 - n*m的二维数组
row = int(input())
column = int(input())
dp = [[i*column + j for j in range(column) ] for i in range(row)]
#第i行第j列元素=元素所在行数*总列数+该元素所在的列数
print(dp)
二:初始化一个元素全为0的二维数组
row = int(input())
column = int(input())
dp = [[0 for j in range(column)] for i in range(row)]
print(dp)
三:手动输入,一个n*m的二维数组(一个一个元素输入)
row = int(input())
column = int(input())
dp = []
array = []
for i in range(row):
for j in range(column):
value = int(input())
array.append(value)
dp.append(array)
array = []
print(dp)
四:手动输入,一行一行输入
'''
例:
输入 3
1 2
3 4
5 6
输出 [[1, 2], [3, 4], [5, 6]]
'''
row = int(input())
dp = []
for i in range(row):
column = list(map(int,sys.stdin.readline().split())) #split默认分隔符为空格
#column = list(map(int, sys.stdin.readline().split(','))) # 以,为分隔符
dp.append(column)
print(dp)
五:手动输入,一行输入全部数据
'''
例:
输入 1 2 3 4 5 6 7 8
4
2
输出 [[1, 2], [3, 4], [5, 6], [7, 8]]
'''
elements = sys.stdin.readline().split()
array = list(map(int,elements))
dp = []
row = int(input())
column = int(input())
for i in range(row):
dp.append(array[i*column:(i+1)*column])
print(dp)