0

I want to convert a normal list(main_list) into a nested one(ans_list) but I don't know how.

main_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ans_list = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Ali
  • 115
  • 5
  • 2
    What's the condition then? Every n-th member? How did you try to do it? – Fabio Craig Wimmer Florey Nov 19 '21 at 13:32
  • 2
    `it=iter(main_list); list(zip(*zip(it, it, it)))` from what I understood. – Ch3steR Nov 19 '21 at 13:33
  • @FabioCraigWimmerFlorey, yes you're right. I mean every n-th number. – Ali Nov 19 '21 at 13:35
  • @Ch3steR, Thank you for your reply. It works indeed. A question, what if I want to have every 100th member? Do I have to write "it" variable 100 times? – Ali Nov 19 '21 at 13:40
  • @Ali No, it was just a fun way to do it. I had the same answer user2390182 posted he was quicker than me to post. Though you could do this, `list(zip(*zip(*[it]*N)))`, let `N` be any number. This is not a pythonic way to do it, just me abusing the language. :) – Ch3steR Nov 19 '21 at 13:44
  • Thank you @user2390182 very much for your helpful answer. – Ali Nov 19 '21 at 13:53
  • @Ch3steR you can golf it even more: `[*zip(*zip(*[iter(main_list)]*n))]`. But I can't adjust it to create lists instead of tuples without resorting to list comprehension! – Fabio Craig Wimmer Florey Nov 19 '21 at 13:59
  • @FabioCraigWimmerFlorey We could use `map`, `[*map(list, zip(*zip(*[iter(main_list)]*n)))]` something like this. – Ch3steR Nov 19 '21 at 14:03
  • @Ch3steR I tried `map` but I kept inverting the `*`! I need way more study and coffee! :D – Fabio Craig Wimmer Florey Nov 19 '21 at 14:07

2 Answers2

6

Use a comprehension over appropriate slices:

n = 3
ans_list = [main_list[i::n] for i in range(n)]
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

if you are open to using NumPy and there are no other conditions other than how many rows you want to split in to then try this

import numpy as np    
np.array(main_list).reshape(-1,3).tolist()
Akshay Kadidal
  • 515
  • 1
  • 7
  • 15