-1

I am new to Python, is there any best way to resolve below issue list slicing

I have main list called

result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]

I would like to slice above list divide 12 and expecting to have the following output:

new_result = {
    'One' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    'Two' : [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
    'Three' : [25, 26]
}
Antoine Dubuis
  • 4,974
  • 1
  • 15
  • 29
  • Check the [recipes section](https://docs.python.org/3/library/itertools.html#itertools-recipes) of the `itertools` module documentation, specifically the `grouper` function. – chepner Nov 01 '20 at 13:43
  • Does this answer your question? [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) – Tomerikoo Nov 01 '20 at 14:13

2 Answers2

0

You can do something like this:

result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
          14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]

chunk_size = 12

splitted_result = [result[x:x+chunk_size]
                   for x in range(0, len(result), chunk_size)]

for chunk in splitted_result:
    print(chunk)

Result:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
[25, 26]

Into the last for loop you can create the object with the correct keys.

The script logic is simple: The range function takes three arguments:

  • start (0)
  • stop (length of the list)
  • step (increment between each returned value)

In your case you will have: range(0, len(result), chunk_size)=[0,12,24] and you just have to split the initial list in chunks that goes from:

result[0:0+12] result[12:12+12] result[24:24+12]

Marco Caldera
  • 485
  • 2
  • 7
  • 16
  • @Student_Learner no need for thank you comments in SO. Please read [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) for other ways to show appreciation around here... – Tomerikoo Nov 01 '20 at 14:26
0

You can do the following:

result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
new_list = [result[n-1:n+11] for n in result[::12]]

new_result = {}
for n in range(1,len(new_list)+1):
    new_result[n] = new_list[n-1]
new_result

{1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
 2: [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
 3: [25, 26]}

The new_list is just the list with the sliced lists. Then, I convert it into a dictionary called new_result, starting from '1' onwards

jlb_gouveia
  • 603
  • 3
  • 11