-2

I have an array that has X number of values.

I'm trying to make an array of arrays with 10 items each of X. How do I go on about in doing something like this?

I've tried using a count while iterating it and let's just say I didn't get anywhere with that.

I want something like

# Random list of 20 items
random_array = [1,...20]

# Do cool things here

# Output after doing cool thing
fancy_array = [[1,...10],[11,..20]]

Athfan
  • 23
  • 4

3 Answers3

0

Python's itertools module is likely to be some help here. Specifically, the grouper recipe

See the recipes in the python docs, but I've copied the relevant one here:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)
Kyle Willmon
  • 709
  • 3
  • 13
-1

Simply do:

fancy_array = [random_array[i:i+10] for i in range(0, len(random_array), 10)]

Explanation

  • range(0, len(random_array), 10) generates a range with the values of the initial indexes where the list must be divided. Since it should be 10 in 10, then the third argument of the function is 10 (called a step).

  • random_array[i:i+10] slices the list in the initial position i and in the final position i+10 to each value generated by the function range.

enzo
  • 9,861
  • 3
  • 15
  • 38
-2

You can do this to split list l in lists of length n like explained here How do you split a list into evenly sized chunks?:

def split_list(l, n):
    n = max(1, n)
    return [l[i:i+n] for i in range(0, len(l), n)]
dome
  • 820
  • 7
  • 20
  • 4
    You should give credit to the [original answer](https://stackoverflow.com/a/1751478/1324033) instead of plagiarising. – Sayse May 02 '19 at 20:46
  • I edited and added the original post. – dome May 02 '19 at 20:48
  • 2
    You copied an answer from the proposed duplicate, a good two minutes AFTER it was proposed. Instead of doing that you should flag as duplicate. – Yunnosch May 02 '19 at 20:51
  • I copied before seeing the comment. Anyway I'm sorry, I'm new here and I didn't know the flags of a question worked. – dome May 02 '19 at 20:55