1

I'd like to get array of numpy arrays with ranged lengths like this:

>>> source = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> get_array_of_arrays_with_min_length(source, 5)
    array([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           [2, 3, 4, 5, 6, 7, 8, 9, 10],
           [3, 4, 5, 6, 7, 8, 9, 10],
           [4, 5, 6, 7, 8, 9, 10],
           [5, 6, 7, 8, 9, 10],
           [6, 7, 8, 9, 10]])

How to do this with less code?

4
  • That looks like array of lists. Can you confirm? Commented Sep 20, 2018 at 13:46
  • A good question might be: what is an array of arrays with dynamic size for you? Depending on what you want NumPy might not be the right tool for you. Commented Sep 20, 2018 at 14:02
  • 1
    There's been many similar questions. Look up ragged arrays Commented Sep 20, 2018 at 14:16
  • Less code than what? You didn't provide anything to compare with. Commented Sep 20, 2018 at 15:45

1 Answer 1

1

Generate your lists,

l = [ [i+1 for i in range(x+1, 10)] for x in range(6)]

Then create your array.

a = numpy.array(l)

If I had to guess what your function should do,

def get_array_of_arrays(source, m):
    return [ [ i for i in source if i>x] for x in range(m+1)]

That would give you the result you've requested from the inputs provided. Really the take-home idea here is to make a list of lists.

Sign up to request clarification or add additional context in comments.

2 Comments

range(x+1:10) is not valid Python, should be range(x+1, 10)
I think a cleaner version of this double range is: [list(range(n, 11)) for n in range(1, 7)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.