Reputation: 53
I have some arrays like these:
a1 = [1,2,3,4]
a2 = [6,7,8,9]
a3 = [2,4,6,8]
a4 = ['Mon','Tues']
I want to group them as
result = [
[[1,6,2,'Mon'],[2,7,4,'Mon']],
[[3,8,6,'Tues'],[4,9,8,'Tues']]
]
which means if I print the 0th row it will output:
[[1,6,2,'Mon'],[2,7,4,'Mon']]
Upvotes: 1
Views: 84
Reputation: 1302
This the code for that:
a1 = [1,2,3,4]
a2 = [6,7,8,9]
a3 = [2,4,6,8]
a4 = ['Mon','Tues']
result=[[],[]]
[result[0].append([a1[i],a2[i],a3[i],a4[0]])if i< 2 else result[1].append([a1[i],a2[i],a3[i],a4[1]])for i in range(len(a1))]
print(result)
It outputs:
[[[1, 6, 2, 'Mon'], [2, 7, 4, 'Mon']], [[3, 8, 6, 'Tues'], [4, 9, 8, 'Tues']]]
Upvotes: 2
Reputation: 2636
Your a4
is of different length, but otherwise, zip
is appropriate function:
>>> a1 = [1,2,3,4]
>>> a2 = [6,7,8,9]
>>> a3 = [2,4,6,8]
>>> a4 = ['Mon','Tues']
>>> a4_long = [item for item in a4 for i in range(len(a1)//len(a4))]
>>>
>>> list(list(l) for l in zip(a1,a2,a3,a4_long))
[
[1, 6, 2, 'Mon'],
[2, 7, 4, 'Mon'],
[3, 8, 6, 'Tues'],
[4, 9, 8, 'Tues']
]
Upvotes: 3