3

I have a list

index = [1, 1, 1, 0, 0] 

and A is the array:

A = [[ 0.  5. 10. 15.]
     [ 1.  6. 11. 16.]
     [ 2.  7. 12. 17.]
     [ 3.  8. 13. 18.]
     [ 4.  9. 14. 19.]]

I basically want to create an array which appends the element of each row according to the index position in the list index. So to create the array [5, 6, 7, 3, 4]. I tried the following nested for loop but it obviously returned the 5 values for each row, rather than the specific one from each row.

list = []
for i in index:
    for a in A:
         list.append(a[i])
2
  • Look into the builtin zip Commented Mar 1, 2020 at 17:40
  • 2
    Are you working with lists or np.arrays? Commented Mar 1, 2020 at 17:41

2 Answers 2

3

Use the builtin zip to iterate both index and A simultaneously:

result = [row[i] for i, row in zip(index, A)]

For added brevity, I've expressed your loop as a list comprehension. Manually iterating over the iterator produced by zip is also perfectly valid:

result = []
for i, row in zip(index, A):
    result.append(row[i])

Also note that it is generally a poor practice to create a variable with same name as a builtin, so I'd advise you rename list to e.g. result, my_list, or a more contextually relevant name.

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

1 Comment

Thanks this worked, and yeah the list is named differently in my code was just simplifying for on here
0

The index of elements in index is the row and their value is the column, so using enumerate you can do:

res = []
for row, col in enumerate(index):
    res.append(A[row][col])

Or as list-comp:

res = [A[row][col] for row, col in enumerate(index)]

2 Comments

enumerate works, but I think using zip is more pythonic.
Yeah I agree that using zip saves the extra A[row]. I will leave this as another approach anyway...

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.