我可以使用列表理解在python中的2D数组中获取输入吗??。以及如何为nD阵列实现它?
假设用户希望输入以下格式 如何在2D数组中获取此输入?nD(n=自然数)数组的列表理解的一般规则是什么??我可以使用列表理解在python中的2D数组中获取输入吗??。以及如何为nD阵列实现它?,python,arrays,python-3.x,list,list-comprehension,Python,Arrays,Python 3.x,List,List Comprehension,假设用户希望输入以下格式 如何在2D数组中获取此输入?nD(n=自然数)数组的列表理解的一般规则是什么?? 请提出建议,谢谢。您可以通过以下方式尝试: out = [] for i in range(n): temp = list(map(int,input().split())) #temp will be [1,1,1,0,0,0] in the first iteration out.append(temp) 将以以下方式进行输出: [[1, 1, 1, 0,
请提出建议,谢谢。您可以通过以下方式尝试:
out = []
for i in range(n):
temp = list(map(int,input().split()))
#temp will be [1,1,1,0,0,0] in the first iteration
out.append(temp)
将以以下方式进行输出:
[[1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 0, 2, 4, 4, 0], [0, 0, 0, 2, 0, 0], [0, 0, 1, 2, 4, 0]
你需要一个循环
user_input = []
while True:
row = input('Next row:\n')
if len(row) == 0:
break
user_input.append([int(x) for x in row.split()])
可以,但必须事先知道尺寸的数量。
与2D 4x4类似:
a=[[int(input()) for x in range(4)] for y in range(4)]
4-s可以是任何东西,但嵌套本身在这样的代码中是固定的
对于任意数量的维度,您可以尝试一点递归:
def nd(dims):
if len(dims) == 0:
return int(input())
return [nd(dims[:-1]) for x in range(dims[-1])]
然后像这样运行它
>>> nd([2,2])
1
2
3
4
[[1, 2], [3, 4]]
对于2x2 2D或 对于2x3x4 3D
>>> nd([2,2])
1
2
3
4
[[1, 2], [3, 4]]
>>> nd([2,3,4])
1
2
3
[...]
23
24
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]], [[13, 14], [15, 16], [17, 18]], [[19, 20], [21, 22], [23, 24]]]