2

Let's say I have an array

a = np.array[5, 3, 2]

and based on that array I want to return a new array in the form:

b = np.array[ [0, 1, 2, 3, 4], [0, 1, 2], [0, 1] ]

I've been trying:

for item in a:
    b = np.hstack(np.arange(item))
    print b

but this only gives me the elements without joining them into an array;

for item in a:
    b = b.append((b[:], b[item]))
    print b

but this approach blows up nicely with a:

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I have tried other things, like:

b[item] = np.arange(item), 

but that one complains about out-of-bounds indices.

And

b = np.zeros(len(a))
for item in np.arange(len(a)):
b[item] = np.arange(b[item])
print b

which complains with

ValueError: setting an array element with a sequence.

That last one is the one that looks more promising and, searching for some questions on this site (https://stackoverflow.com/a/13311979/531687) I know that the problem is that I am trying to fit a sequence where a value is expected, but I can't figure out my way around it.

How can I go about this?

1 Answer 1

3

This should work

b = [range(x) for x in a]

update

The brackets [...] here create a list and inside an iterator can be used to define the items in the list. In this case the items of of type range(x) for each item in a.

Note that there is a difference in implementation between python2 and python3 here. In python2 this actually generates a list of lists. In python3 however this generates a lists of generators (the python2 equivalent would be xrange), which is typically more efficient.

1
  • That worked perfectly! Would you mind adding a bit of an explanation? As I am understanding this, range(x) is being fed the items in a, but I can't quite grasp how it is grouping them into a list.
    – Ricardo
    Oct 27, 2013 at 22:01

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.