为什么我的函数写一个值代替另一个值?

时间:2019-01-31 21:35:50

标签: python python-3.x

我在.txt文件中有一个Vehicle数据库。 每条线都有不同的车辆。 每辆车都有x值和y值(默认均为2.5) 每辆车的x和y都应> = 0和<= 5(并且最大为十进制数字)。

我希望我的refresh()函数使用新的x和y坐标随机地重新分配每条线(每辆车)。

该功能还可以,但是在文本文件中,尽管每行具有不同的值,但每行的x和y值相同。

我得到类似的东西

第1行:x = 0.8 | y = 0.8

第2行:x = 4.1 | y = 4.1

我想要的是这样的

第1行:x = 0.3 | y = 3.1

第2行:x = 2.4 | y = 1.7

def refresh():
    new_positions = []
    with open("Vehicles.txt", "r") as file:
        lines = file.readlines()
        for line in lines:
            old_line = line.split(" | ")
            x_to_change = old_line[14]
            y_to_change = old_line[15]
            pre_random_x = random.uniform(0, 5)
            pre_random_y = random.uniform(0, 5)
            random_x = str(round(pre_random_x, 1))
            random_y = str(round(pre_random_y, 1))
            new_line = line.replace(x_to_change, random_x)
            new_line_2 = new_line.replace(y_to_change, random_y)
            new_positions.append(new_line_2)
    with open("Vehicles.txt", "w") as file:
        file.writelines(new_positions)
        print("VEHICLE POSITIONS SUCCESSFULLY REFRESHED.\n")

1 个答案:

答案 0 :(得分:5)

在原始文本文件中,x和y都默认为2.5。

new_line = line.replace(x_to_change, random_x)

每个的外观从2.5更改为random_x-都是数字。

最好将它们默认为不同的数字,或者为时已晚,请使用

重新创建新行
new_line = ' | '.join(old_line[:14] + [random_x, random_y] + old_line[16:])

甚至

old_line[14:16] = [random_x, random_y]
new_line = ' | '.join(old_line)

在两种情况下,结果都不取决于字段中的原始值。