从单个输入整数列表创建2D数组,输入整数之间用空格隔开 [英] Creating a 2D array from a single list of input integers separated by space

查看:99
本文介绍了从单个输入整数列表创建2D数组,输入整数之间用空格隔开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在geeksforgeeks处解决了一些问题,遇到一个特殊的问题,其中在测试用例中提供了输入,如下所示:

I was solving some problems at geeksforgeeks and I came across a particluar question where the inputs are provided in the test case as shown:

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.

我不知道如何使用以这种方式给出的输入来初始化我的2D数组.

I am not getting how to initialize my 2D array with the inputs given in such a manner.

P.S.我不能使用split,因为它将在一个数组中拆分所有元素,因此我必须从中再次读取每个元素.我正在寻找更简单和Pythonic的方式.

P.S. I can't use split as it will split all the elements on in a single array from which I have to read again each element. I am looking for more simple and pythonic way.

推荐答案

您应使用.split.并且您还需要将拆分的字符串项转换为int.但是,如果您愿意,则可以非常紧凑地做到这一点:

You should use .split. And you also need to convert the split string items to int. But you can do that very compactly, if you want to:

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,请将其更改为


If you get a SyntaxError on mat = [*map(list, zip(*[data] * cols))] change it to

mat = list(map(list, zip(*[data] * cols)))

或升级到较新的Python 3.;)

Or upgrade to a newer Python 3. ;)

这篇关于从单个输入整数列表创建2D数组,输入整数之间用空格隔开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆