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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

There are some differences. I expect the a4 should like this:[ [[1,6,2,'Mon'],[2,7,4,'Mon']], [[3,8,6,'Tues'],[4,9,8,'Tues']] ] more specific, [[1,6,2,'Mon'],[2,7,4,'Mon']], two 'Mon's in the same array
Sure, you need to convert tuple into list, if you need that
but two 'Mon's in the different array?
oh, just noticed, let me think
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']]]

3 Comments

the output is not what I expect... It should be like this: [[1,6,2,'Mon'],[2,7,4,'Mon']]
I made it, Can you please check?
It's a bad practice and very anti-pythonic to use list comprehensions for just side effects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.