Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

python - Simplify list comprehension when a call to function returning a tuple is necessary

I have the following function:

def get_cofactors_matrix(self) -> 'Matrix':
    """Returns the cofactors matrix"""
cofactors = [list(map(lambda x: x[1] * x[2],  [self.get_cofactor_at(i, j) for j in range(self.get_columns_count())])) for i in range(self.get_lines_count())]
...

I would like to simplify the list comprehension, the get_cofactor_at(line, column) return a tuple of 3 values so without using list comprehension this code can be expressed in the following way:

    result = []
    for i in range(lines):
        result_line = []
        for j in range(columns):
            _, x, y = self.get_cofactor_at(i, j)
            result_line.append(x * y)
            
        result.append(result_line)

What would be a better expression ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would isolate the dimensions and use a comprehension instead for list(map(lambda...

lines,cols = self.get_lines_count(),self.get_columns_count()
cofactors  = [[x*y for _,x,y in self.get_cofactor_at(i, j) for j in range(cols)] 
                                                           for i in range(lines)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...