Converting 2D array into [ [ x0 y0 ] [x1 y1] [x2 y2] ] form

Viewed 116

In Python, I am looking to convert the array:

[[1, 2, 3, 4, 5],[10, 20, 30, 40, 50]]

into

[[1 10][2 20][3 30][4 40][5 50]]

Is there an easy way to do this? And what is the technical name for the second type of array?

NOT

[[1, 10][2, 20][3, 30][4, 40][5, 50]]
4 Answers
>>> ans = []
>>> list1 = [1, 2, 3, 4, 5]
>>> list2 = [10, 20, 30, 40, 50]
>>> for a, b in zip(list1, list2):
...   ans.append([a,b])
... 
>>> ans
[[1, 10], [2, 20], [3, 30], [4, 40], [5, 50]]

You can use zip to get the result

arr = [[1, 2, 3, 4, 5],[10, 20, 30, 40, 50]]
result = [list(x) for x in zip(*arr)]

try this

ls =[[1, 2, 3, 4, 5],[10, 20, 30, 40, 50]]

res = [list(x) for x in zip(*ls)]

new_list = []
for i in res:
    item = ''.join(str(i).split(','))
    new_list.append(item)
print(new_list) #['[1 10]', '[2 20]', '[3 30]', '[4 40]', '[5 50]']

after join new_list,it look like

print([''.join(new_list)]) #['[1 10][2 20][3 30][4 40][5 50]']

There is not MATLAB's like syntax in Python, you cannot define list or arrays like this.

A = [[1 2 3], [4 5 6]]

You must separate every value by comma.

Related