0

I am having a list named "V_List" which I am needed to build up a nested list.

    V_List = [145, 554, 784, 598, 632, 456, 8989, 123, 777]

I want to have my nested list as following,

   result = [ [145, 598, 8989], [554, 632, 123], [784, 456, 777] ]

It should be having a pattern something like this, the 1st element should be gone to the 1st nested list, the 2nd element should be gone to the 2nd nested list, 3rd element should be gone to the 3rd nested list, and again the 4th should go to the 1st nested list....

How can I do something like this?

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
Shakya_A
  • 17
  • 4
  • 2
    what is the criteria for the nesting? any three items in the sub list? – MEdwin Nov 29 '18 at 11:57
  • @MEdwin - No, not any three items. It should be having a pattern something like this, the 1st element should be gone to the 1st nested list, the 2nd element should be gone to the 2nd nested list, 3rd element should be gone to the 3rd nested list, and again the 4th should go to the 1st nested list.... – Shakya_A Nov 29 '18 at 12:00
  • 1
    Possible duplicate of [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – Azat Ibrakov Nov 29 '18 at 12:06
  • @AzatIbrakov, it has a twist though.... the split allocation. – MEdwin Nov 29 '18 at 12:24

4 Answers4

3

So you are looking for this:

total_lists = 3
result = [V_List[i::total_lists] for i in range(total_lists)]
result
#[[145, 598, 8989], [554, 632, 123], [784, 456, 777]]

So, you can control the resulting number of lists using the total_lists variable.

zipa
  • 27,316
  • 6
  • 40
  • 58
1

-- Edited to fit EvilSmurf's comment for Python3 support import math [[V_List[j * 3 + i] for j in range(math.ceil(len(V_List) / 3))] for i in range(3)]

Explanation:

List comprehension for every % value (for i in range 3) taking the list of relevant items using another list comprehension.

Result:

[[145, 598, 8989], [554, 632, 123], [784, 456, 777]]

Shushan
  • 1,235
  • 1
  • 10
  • 15
  • 1
    in python 3 you need to cast indexes and range specifiers to integer [[V_List[j * 3 + i] for j in range(int(len(V_List) / 3))] for i in range(3)] – EvilSmurf Nov 29 '18 at 12:05
0

try this.

nested = [[], [], []]
for item in V_List:
    nested[V_list.index(item) % 3].append(item)
ozata
  • 542
  • 1
  • 5
  • 16
0

You can combine list-comprehension and zip together:

V_List = [145, 554, 784, 598, 632, 456, 8989, 123, 777]

V_List_splited = [list(i) for i in zip(V_List[:3] , V_List[3:6] , V_List[6:])]
print(V_List_splited)

Output :

C:\Users\Desktop>py x.py
[[145, 598, 8989], [554, 632, 123], [784, 456, 777]]
Rarblack
  • 4,559
  • 4
  • 22
  • 33