简体   繁体   中英

How can I iterate through the indices of the list?

I am trying to compute three lists for example

M =[[3, 0, 2, -8, -8], [5, 3, 2, 2, 3], [2, 5, 2, 1, 4]]

I want to first sum every first value in the list x=3+5+2

and the rest values in all the lists add them together as y

finally the difference of absolute value of xy which is 10 - 8

and again sum every first two values in the list x=3+5+2+0+3+5

and the rest values in all the lists add them together as y

finally the difference of absolute value of xy which is 18 - 0

again the same process until the last value in the list

lastly If difference is the minimum stored value, set the minimum value to difference and the minimum index to index, and finally return the slices found by getting the minimum value

for this example slices found is list1=[3,5,2] list2=[0,2,-8,-8,3,2,2,3,2,5,2,1,4] i calculated it manually but i couldn't implement it

 def Vertical_UpperMatrix(M):
        ds=range(5)
        diffList = [(abs(sum(ds[:i]) - sum(ds[i:]))) for i in range(3)]
        return diffList.index(min(diffList))
 M=[[3, 0, 2, -8, -8], [5, 3, 2, 2, 3], [2, 5, 2, 1, 4]]

I am in EST timezone, so at the time this answer is written, it is 2:40am. But I am taking time to answer, basically to repay your willingness to improve.

We will use a library called numpy . If you don't have numpy on your machine, please Google-Search how you can install it on your OS. It is important for your career onwards, and you will see why.

First, create your numpy array:

>>> import numpy as np
>>> l = np.array([[3, 0, 2, -8, -8], [5, 3, 2, 2, 3], [2, 5, 2, 1, 4]])
>>> l
array([[ 3,  0,  2, -8, -8],
       [ 5,  3,  2,  2,  3],
       [ 2,  5,  2,  1,  4]])

Now you can access the first column by doing

>>> l[:, 0]
array([3, 5, 2])

The first row can be accessed by

>>> l[0, :]
array([ 3,  0,  2, -8, -8])

The first row from the second element to the fourth element by

>>> l[0, 1:4]
array([ 0,  2, -8])

Based on all the features above, the target function you want is basically this:

>>> d = 1
>>> np.abs(np.sum(l[:, 0:d]) - np.sum(l[:, d:]))
2

d is your dividing index. Now you can iterate over d in a for loop.

I suggest you learn about at least numpy and scipy if you plan to carry on your career with Python .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM