Skip to main content
 首页 » 编程设计

python之为什么这个 python 代码只产生最后的结果

2025年05月04日20bluestorm

我想计算满足条件的矩阵:
result_x = 1 - initial_x;
result_y = initial_y 和
results_z = initial_y.
但是,我的代码只产生每个数组的最后一个。你能帮帮我吗?

import numpy as np 
import math 
 
def reverse_a_direction(matrix): 
    reverse_a = [] 
    for (x, y, z) in matrix: 
        reverse_a = 1 - x, y, z 
    return reverse_a 
 
a = np.array([[(0.1666666666666667, 0.8012144614989793, 0.7500000000000000),  
               (0.1666666666666667, 0.1987855385010207, 0.2500000000000000)],  
              [(0.6666666666666666, 0.3012144614989793, 0.7500000000000000),  
               (0.6666666666666666, 0.6987855385010207, 0.2500000000000000)]]) 
 
for i in range(0, len(a)): 
    print(reverse_a_direction(a[i])) 

这段代码的结果:

(0.8333333333333333, 0.1987855385010207, 0.25) 
(0.3333333333333333, 0.6987855385010207, 0.25) 

预期结果:

[(0.8333333333333333, 0.8012144614989793, 0.75), (0.8333333333333333, 0.1987855385010207, 0.25)], 
[(0.3333333333333333, 0.3012144614989793, 0.75), (0.3333333333333333, 0.6987855385010207, 0.25)] 

请您参考如下方法:

每次迭代都会覆盖 reverse_a。正确的解决方案是:

def reverse_a_direction(matrix): 
    reverse_a = [] 
    for (x, y, z) in matrix: 
        a = 1 - x, y, z 
        reverse_a.append(a) 
    return reverse_a