Python - 为什么列表中的每个项目都被 while 循环的最终值覆盖?[复制]

Python - Why is every item in my list being overwritten by the final value of my while loop? [duplicate]

提问人:jessicashew 提问时间:2/13/2022 更新时间:2/13/2022 访问量:44

问:

我正在尝试从加速度计值计算位置。为此,我将每个加速度输出与时间戳一起附加到嵌套列表中,然后使用它们来计算速度和位置。我遇到了一个问题,即我在速度列表中附加的每个值都会被 while 循环中的最终速度输出覆盖。有没有办法保留循环每次迭代的速度值列表,而不会改变其值?

import time
from random import randint
acceleration_list = []
velocity_list = []
velocity = [[0,0,0],0]

index = 0

while index < 10:
    
    # Get current acceleration and append to list
    accel = [randint(-5,5),randint(-5,5),randint(-5,5)]              # Accelerometer Values 
    accel[1] -= 1                                                    # Subtract 1g from Y-value

    time_stamp = time.time()                                       # Time stamp
    curr_acceleration = [accel, time_stamp]                        # List to store accelerometer values + time stamp
    acceleration_list.append(curr_acceleration)                    # Add to total acceleration list
    # print(f"Acceleration values are: {acceleration_list}")
    time.sleep(0.025)
    # Calculate velocity using acceleration
    
    for i in range(3):
        if len(acceleration_list) > 1 and index > 0:                # Wait until we've done one iteration
            if abs(acceleration_list[index][0][i]) < 0.5:           # Filter out small values from the accelerometer
                acceleration_list[index][0][i] = 0.0
            # Previous Velocity + (Current Acceleration + Previous Acceleration / 2 ) * (Current Time - Previous Time) 
            velocity[0][i] = velocity_list[index-1][0][i] + ((acceleration_list[index][0][i] + acceleration_list[index-1][0][i])/2)*(acceleration_list[index][1] - acceleration_list[index-1][1])
    velocity[1] = acceleration_list[index][1]
    velocity_list.append(velocity)
    print(velocity)
    
    index += 1
print(velocity_list)
列表 不变性 可变

评论

1赞 donkopotamus 2/13/2022
你认为在循环的每次迭代中,这是一个不同的列表吗?它实际上可能是每次迭代中的相同列表实例吗?velocity
1赞 Karl Knechtel 2/13/2022
每次通过循环,都是同一个对象不复制值;它将该对象放入列表中 - 同一对象,多次。如果更改该对象,则会多次看到更改,因为您正在对同一对象进行多次查看。velocity.append

答: 暂无答案