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
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.
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]]
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)
© 2024 OneMinuteCode. All rights reserved.