-1

I worked in Python 3.6, and I am a beginner. So can anyone give me a true way of how can slice a list into variable size sub-list. I tried this solution from this site, but it gave me fixed size of sliced list. To clarify:

if I have this list:

inputList= [0,1,2,3,4,5,6,7]

I want the output to be like e.g.:

outputList=[[0,1,2], [3,4], [5], [6,7]]

each time it depends on (for example) user input or some variable size.

Nujud Ali
  • 135
  • 2
  • 9
  • 2
    How do you decide the slices? Your example doesn't offer us much to help you with. – jacoblaw Nov 20 '17 at 23:45
  • for example in my own project I want to slice the list of number based on count of word occurrences in a text comes after a word. so this is not matter actually because I need the idea. i.e. let word occurrences = n, so whatever n is equal to? the list should slice in a sub-list based on n with its variable size each time as I mentioned above. i hope that is clear I don't no how can i explain it to you. – Nujud Ali Nov 20 '17 at 23:57

3 Answers3

3

Just use itertools.islice(). This has the added advantage that if you request a slice that you would normally take you out of bounds, you won't get an error. You'll just get as many items are left as possible.

>>> import itertools as it
>>> input_list = range(8)
>>> slices = (3, 2, 1, 2)
>>> iterable = iter(input_list)
>>> output_list = [list(it.islice(iterable, sl)) for sl in slices]
>>> output_list
[[0, 1, 2], [3, 4], [5], [6, 7]]

For example, if you had slices = (3, 2, 1, 3, 2), your result would be [[0, 1, 2], [3, 4], [5], [6, 7], []].

Basically, iter(input_list) creates an iterable of your list so you can fetch the next k values with islice().

Reti43
  • 9,656
  • 3
  • 28
  • 44
1

You can do this in a loop making use of python's [:#] slice notation:

Let's say the user's input for slicing chunk sizes is stored in a list. They want chunks of 3, 2, 1 and 2, so the user input defining the chunks gets stored into a list that has has [3,2,1,2].

Then, loop through that list and use it to get your slices:

input_list = [0,1,2,3,4,5,6,7]
chunk_list = [3,2,1,2]
output_list = []
for i in chunk_list:
    output_list.append(input_list[:i])
    input_list = input_list[i:]
print(output_list)

Prints:

[[0, 1, 2], [3, 4], [5], [6, 7]]
Davy M
  • 1,697
  • 4
  • 20
  • 27
0

Probably you just want to learn about slicing. See Understanding Python's slice notation

To get your example output, you could do

outputList = [inputList[:3], inputList[3:5], inputList[5:6], inputList[6:]]
Tim Hoffmann
  • 1,325
  • 9
  • 28