0

If I have a nested array lets say:

arr = [[1, 2, 3, 4], [5, 6, 7, 8]]

I want to divide element wise so my output would be:

[5/1, 6/2, 7/3, 8/4]

Just using fractions to be clear on what I'm asking.

1
  • 3
    [b/a for a,b in zip(*arr)] Commented Oct 27, 2021 at 6:03

2 Answers 2

1

Try to use the zip() function:

d=[] #This is done to avoid name 'd' is not defined
arr = [[1, 2, 3, 4], [5, 6, 7, 8]]
zipped = zip(arr[1], arr[0])
for i1,i2 in zipped:
    d.append(i1/i2)
Sign up to request clarification or add additional context in comments.

2 Comments

Would you know If I had a large number of rows and wanted to use a for loop how would I accomplish this since I wouldn't be able to use zip?
If you don't want to use zip() you could iterate through the first list with enumerate() and then access the second list with the counter.
0

You can easily do this with numpy.

Extract the second row, and divide it by the first row element wise:

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
np.array(arr[1, :] / arr[0, :])
# [5.         3.         2.33333333 2.        ]

If instead you want to do it with a for loop:

[arr[1][i] / arr[0][i] for i in range(len(arr[0]))]

2 Comments

Thank you. Do you know what i would do if I had a large number of rows, and wanted to use a for loop?
I've edited my post to show a for loop approach as well, or I would use @luigigi's approach

Your Answer

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