【问题标题】:Creating a 2D array from a single list of input integers separated by space从由空格分隔的单个输入整数列表创建二维数组
【发布时间】:2018-05-13 02:59:53
【问题描述】:
我在geeksforgeeks 解决了一些问题,遇到了一个特殊的问题,其中输入是在测试用例中提供的,如图所示:
2 2 # denotes row, column of the matrix
1 0 0 0 # all the elements of the matrix in a single line separated by a single space.
我不知道如何使用以这种方式给出的输入来初始化我的二维数组。
附:我不能使用 split 因为它会将所有元素拆分到一个数组中,我必须从中再次读取每个元素。我正在寻找更简单和pythonic的方式。
【问题讨论】:
标签:
python
arrays
python-3.x
input
【解决方案1】:
您应该使用.split。您还需要将拆分的字符串项转换为int。但是,如果您愿意,您可以非常紧凑地做到这一点:
rows, cols = map(int, input('rows cols: ').split())
data = map(int, input('data: ').split())
mat = [*map(list, zip(*[data] * cols))]
print(rows, cols)
print(mat)
演示
rows cols: 2 2
data: 1 2 3 4
2 2
[[1, 2], [3, 4]]
如果您在 mat = [*map(list, zip(*[data] * cols))] 上收到 SyntaxError,请将其更改为
mat = list(map(list, zip(*[data] * cols)))
或者升级到更新的 Python 3。;)
【解决方案2】:
在两个字符串上使用 split 后:
n_rows, n_cols = [int(x) for x in matrix_info_str.split(' ')]
split_str = matrix_str.split(' ')
我同意:
matrix = [split_str[i : i + n_cols] for i in xrange(0, n_rows * n_cols, n_cols)]