Home > Enterprise >  Nested arrays in python
Nested arrays in python

Time:10-27

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. Thank you

CodePudding user response:

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)

CodePudding user response:

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]))]
  • Related