简体   繁体   中英

Dividing certain members of a list in python

I have a matrix formed by a list of lists and I want to divide each member of the second half of each sublist by the integer in the first 3 members of each sublist. Here is my code:

def matrix():

    a=[[12.0, 0.0, 0.0, 12, 156, -108], [0.0, 2.667, 0.0, -5.333, -77.333, 53.333], [0.0, 0.0, -0.0937, -0.0937, -1.4687, 1.0]]

    for i in range(len(a)):
        a[i] = [v/a[i][i] for v in a[i]]

    return a   

However, this code divides each entire sublist by the integer found in the first half of each sublist which gives me this output:

[[1.0, 0.0, 0.0, 1.0, 13.0, -9.0], [0.0, 1.0, 0.0, -1.9996250468691417, -28.996250468691414, 19.99737532808399], [-0.0, -0.0, 1.0, 1.0, 15.674493062966913, -10.672358591248665]]

I only want the second part of each sublist divided, not the first half. I need to obtain this output, as you can see the first 3 integers of each sublist must stay the same:

[[12,0,0,1,13,-9],[0,2.667,0,-2,-29,20],[0,0,-0.09375,1,15.6667,-10.6667]]

You can split up your logic into two steps:

  1. Find the integer in the first three numbers.

  2. Divide the second half of each sublist by that number.

     def matrix(): a = [[12.0, 0.0, 0.0, 12, 156, -108], [0.0, 2.667, 0.0, -5.333, -77.333, 53.333], [0.0, 0.0, -0.0937, -0.0937, -1.4687, 1.0]] for i in range(len(a)): divisor = 0 for j in range(3): if a[i][j]: divisor = a[i][j] break for j in range(len(a[i]) // 2, len(a[i])): a[i][j] = a[i][j] / divisor return a print(matrix())

Output:

[[12.0, 0.0, 0.0, 1.0, 13.0, -9.0], [0.0, 2.667, 0.0, -1.9996250468691417, -28.996250468691414, 19.99737532808399], [0.0, 0.0, -0.0937, 1.0, 15.674493062966913, -10.672358591248665]]

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