简体   繁体   中英

Can I Use the List Comprehensions for taking input in the 2D Array in the python ??. And how it can be implemented for the nD array?

Suppose The user wants to give an input below format.

用户输入的格式

How to take this input in the 2D array? And what is the general rule of List comprehension for the nD (n = Natural Number) Array?? Please Suggest, Thank You.

n = 4    
a = [[int(input()) for j in range(n)] for i in range(n)]

You can try in this way:

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)

Out will be in the following way:

[[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]

You will need a loop for that.

user_input = []
while True:
    row = input('Next row:\n')
    if len(row) == 0:
        break
    user_input.append([int(x) for x in row.split()])

Yes, you can, but you have to know the number of dimensions in advance.
Like for 2D 4x4:

a=[[int(input()) for x in range(4)] for y in range(4)]

The 4-s could be anything, but the nesting itself is fixed in such code.

For arbitrary number of dimensions you can try a bit of recursion:

def nd(dims):
  if len(dims) == 0:
    return int(input())
  return [nd(dims[:-1]) for x in range(dims[-1])]

and run it like

>>> nd([2,2])
1
2
3
4
[[1, 2], [3, 4]]

for 2x2 2D
or

>>> 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]]]

for 2x3x4 3D.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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