Python通过键盘输入二维列表

您所在的位置:网站首页 python输入二维数组。回车结束 Python通过键盘输入二维列表

Python通过键盘输入二维列表

2024-07-07 23:06| 来源: 网络整理| 查看: 265

Python通过键盘输入二维列表

前两天刷笔试题在用python进行二维列表输入时遇到问题后进行了总结。 如输入一个n×n的矩阵存储到二维列表,第一行表示输入参数n,下面为矩阵参数,以3×3为例: 3 1,2,3 4,5,6 7,8,9

1. 以字符形式存入二维列表

n = int(input()) #输入参数 n testList = [[]for i in range(n)] #创建二维列表 for i in range(n): testList[i] = input().split(',') #输入矩阵参数,以','分开两个数 print(testList)

结果:[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

2. 以数字形式存入列表 2.1 方法一 用list()和map()函数,list用于将map()映射输入后的得到的迭代器转换为列表形式。

n = int(input()) testList = [[]for i in range(n)] for i in range(n): testList[i] = list(map(int,input().split(','))) print(testList)

结果:[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 2.2 方法二 用eval()函数,将字符串转换为列表

n = int(input()) testList = [[]for i in range(n)] for i in range(n): testLine[i] = [eval(x) for x in input().split(',')] print(testList)

结果:[[1, 2, 3], [4, 5, 6], [7, 8, 9]]



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3