i have 3 different arrays that i want o join in one array in a specified format Example:
arr_1 = [A,B,C]
arr_2 = [1,2,3]
arr_3 = [E,F,G]
and i want the result array to be like this
arr_result = [[A,1,E],[B,2,F],[C,3,G]]
CodePudding user response:
arr_1 = ['A','B','C']
arr_2 = [1,2,3]
arr_3 = ['E','F','G']
arrays = [arr_1,arr_2,arr_3]
print([[arr[i] for arr in arrays] for i in range(3)])
>> [['A', 1, 'E'], ['B', 2, 'F'], ['C', 3, 'G']]
CodePudding user response:
This list generator should do the trick:
arr_1 = ['A','B','C']
arr_2 = [1,2,3]
arr_3 = ['E','F','G']
arrays = [arr_1,arr_2,arr_3]
print([[arr[i] for arr in arrays] for i in range(3)])
>> [['A', 1, 'E'], ['B', 2, 'F'], ['C', 3, 'G']]
CodePudding user response:
There are some ways you can achieve this of of them is to use zip function here is an example
arr_1 = ['A', 'B', 'C']
arr_2 = [1, 2, 3]
arr_3 = ['E', 'F', 'G']
arr_result = []
for a, b, c in zip(arr_1, arr_2, arr_3):
arr_result.append([a, b, c])
print(arr_result)
in this example, the code will iterate over the elements of each array and create a new array with the elements from each array. This code assumes that arrays are same length.
another way is using list comprehension
arr_1 = ['A', 'B', 'C']
arr_2 = [1, 2, 3]
arr_3 = ['E', 'F', 'G']
arr_result = [[a, b, c] for a, b, c in zip(arr_1, arr_2, arr_3)]
print(arr_result)
CodePudding user response:
arr1 = ["A", "B", "C"]
arr2 = [1, 2, 3]
arr3 = ["E", "F", "G"]
arr4 = [[ *i ] for i in zip(arr1, arr2, arr3)]
Output:
[['A', 1, 'E'], ['B', 2, 'F'], ['C', 3, 'G']]