简体   繁体   English

如何在 python 的列表中输入所有输入都在一行中?

[英]How to take input in list in python in which all input are in one line?

s=input().split()
n,m=int(s[0]),int(s[1])
arr=(int(i) for i in s[2:])

input like输入喜欢

3 4 1 2 3 4 5 6 7 8 9 10 11 12

in this first two are row and column and remaining are 2d list element在这前两个是行和列,其余的是二维列表元素

output be like output 就像

[[1,2,3,4],[5,6,7,8],[9,10,11,12]]

Following your code:按照您的代码:

arr = list(arr)
blocks = [arr[i:i+m] for i in range(0, len(arr), m)]
assert len(blocks) == n

If numpy is an option, you can simply reshape the 1D array:如果numpy是一个选项,您可以简单地重塑一维数组:

s = input().split()
n,m = int(s[0]),int(s[1])
arr = numpy.array(s[2:], dtype=int).reshape((n,m))

You can output it as a numpy array您可以将 output 它作为 numpy 数组

print(arr)
# array([[ 1,  2,  3,  4],
#       [ 5,  6,  7,  8],
#       [ 9, 10, 11, 12]])

or convert it to a nested list或将其转换为嵌套列表

print(arr.tolist())
# [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

Try this way:试试这个方法:

s = input().split()
s = list(map(int, s))
[s[2 + (i - 1) * s[1]: 2 + i * s[1]] for i in range(1, s[0] + 1)]

Output: Output:

[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM