I want to convert a three-dimensional array into a two-dimensional array with python.

Asked 2 years ago, Updated 2 years ago, 28 views

I want python to convert 3D arrays into 2D arrays.

 li = [[[1,2], [2,5,8]], [[1,5,9], [9,10,11], [11,13]], [[2,6,12], [12,17,15], [15,3,2]]]]    

li = [[1,2,5,8], [1,5,9,10,11,13], [2,6,12,17,15,3,2]]    

I would like to convert it as shown in the example above.Thank you for your cooperation.

python

2022-09-30 21:11

3 Answers

li[i][j][-1] and li[i][j+1][0] have the same value.

>>[sum([y[:-1]for y in x[:-1]],[])+x[-1]for x in li]
[[1, 2, 5, 8], [1, 5, 9, 10, 11, 13], [2, 6, 12, 17, 15, 3, 2]]

Or

>>[x[0]+sum([y[1:]for y in x[1:],[])for x in li]
[[1, 2, 5, 8], [1, 5, 9, 10, 11, 13], [2, 6, 12, 17, 15, 3, 2]]

KFrom Kenji Noguchi's comment

Then print[sum([y[1:]for y in x[1:], x[0])for x in li] This may be the simplest.


2022-09-30 21:11

This is what happens when implemented as per data.

>>li=[[[1,2],[2,5,8]],[[1,5,9],[9,10,11],[11,13]],[[2,6,12],[12,17,15],[15,3,2]]]]]    
>>> result=[ ]
>> for x in li:
...     r = [ ]
...     for y in x:
...         if r[-1] == y[0]:
...             r.extend(y[1:])
...         else:
...             r.extend(y)
...     result.append(r)
...
>>>
[[1, 2, 5, 8], [1, 5, 9, 10, 11, 13], [2, 6, 12, 17, 15, 3, 2]]


2022-09-30 21:11

I solved it without a loop.

 li = [[[1,2], [2,5,8]], [[1,5,9], [9,10,11], [11,13]], [[2,6,12], [12,17,15], [15,3,2]]]]
print map(lambdae:reduce(lambdaa,b:a+b[1:],e),li)


2022-09-30 21:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.