在python中将整数转换为空格分隔的列表
我的意见如下: 第一行包含两个空格分隔的整数N和M。下一行是矩阵A的NxM输入: 输入: 我希望输出为列表的列表(整数) 输出:在python中将整数转换为空格分隔的列表,python,python-3.x,list,arraylist,input,Python,Python 3.x,List,Arraylist,Input,我的意见如下: 第一行包含两个空格分隔的整数N和M。下一行是矩阵A的NxM输入: 输入: 我希望输出为列表的列表(整数) 输出: [[1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0]] 将输入读取为字符串。然后可以使用此代码段获取输出 op_list = [] def to_list(number): return [int(dig) for dig in number] op_list.appen
[[1, 1, 1, 1, 0],
[1, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]
将输入读取为字符串。然后可以使用此代码段获取输出
op_list = []
def to_list(number):
return [int(dig) for dig in number]
op_list.append(to_list("11110"))
op_list.append(to_list("11010"))
op_list.append(to_list("11000"))
op_list.append(to_list("00000"))
print(op_list)
假设
input.txt
文件与.py
文件位于同一目录中,并包含以下内容:
4 5
11110
11010
11000
00000
您可以使用以下内容将矩阵作为列表列表:
with open('./input.txt', 'r') as file:
lines = file.readlines()
header = lines[0]
num_rows, num_cols = (int(x) for x in header.split(' '))
print(num_rows, num_cols)
matrix = []
for i in range(1, len(lines)):
line = lines[i]
line = line.rstrip() # get rid of '\n'
as_nums = [int(num) for num in line]
assert len(as_nums) == num_cols
matrix.append(as_nums)
assert len(matrix) == num_rows
在竞争编码中,输入如下所示: 试试看:
n,m = map(int, input().split())
mat = []
for i in range(n):
row = list(map(int,list(input())))
mat.append(row)
print(mat)
mat:
[[1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0]]
[[1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0]]
您可以通过以下方法对其进行测试:
inp=input()
行,列=映射(int,inp.split())
行=[]
对于范围内的i(行):
line=input()[:列]
行。追加([int(l)表示行中的l])
打印(行)
输入:
4 5
11110
11010
11000
00000
输出:
[[1, 1, 1, 1, 0],
[1, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]
[[1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0]]