1

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']]
YCCLLL
  • 53
  • 5

2 Answers2

3

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']
]

avloss
  • 2,389
  • 2
  • 22
  • 26
2

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']]]
Osadhi Virochana
  • 1,294
  • 2
  • 11
  • 21