1

Suppose I have a numpy array like this:

arr = np.array([[1,1,1,1], [2,2,2,2], [3,3,3,3], [4,4,4,4])

I also have a list that determines the intended lengths:

lens = [1,2,3,4] 

Is there an elegant and Pythonic way to return a new array, with each corresponding element selected using the lens variable?

The output should be:

[[1], [2,2],[3,3,3], [4,4,4,4]]

3 Answers 3

5

If each Numpy arr list element size is less than 5 this works.

Use zip:

[a[:i].tolist() for a, i in zip(arr, lens)]

Output:

[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
Sign up to request clarification or add additional context in comments.

1 Comment

Not sure if each arr list elements size is more than or equal to 5 not working. Attribute Error coming
0

This could be a possible solution:

res = []
for a,i in zip(arr, lens):
    res.append(a[:i].tolist())
print(res)

2 Comments

This doesn't print any output as of now. So I edited it to print output by declaring a res variable which is an empty list to start with.
Using your method, the output is like this [[1]] [[1], [2, 2]] [[1], [2, 2], [3, 3, 3]] [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
0

Assuming arr is equal in length as lens:

[arr[i][:v].tolist() for i,v in enumerate(lens)]

Output: [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

Comments

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.