在解析文本文件时意外覆盖变量(python)

2024-10-03 19:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将一个包含数据列的文本文件解析为曲线(x和y值),但是在检查它们时,所有曲线的值都是相同的,尽管我觉得它们不应该

下面是我的代码中可以显示问题的最小值:

    #creates the curves and sets their names given the first row in the text document
    for i, title in (enumerate(titles)):
        curveToAdd = Curve(titles[i].split()[0], UnitData(), UnitData())
        curveToAdd.yUnitData.unit = title.split()[1][1:-1]
        curveToAdd.xUnitData.unit = titlesWithTime[0].split()[1][1:-1]
        tempParsedCurves.append(curveToAdd)

    while isReading:
        text = f.readline()
        dotText = text.replace(",", ".").replace(".00", ".0")
        parts = dotText.split()

        # goes through the values in the current row
        for i, part in enumerate(parts):
            for j, tempParsedCurve in enumerate(tempParsedCurves):
                if len(parts) == len(titles) + 1: #incomplete rows teremine when to stop reading
                    #the current value is for the current curve
                    if tempParsedCurve.name == tempParsedCurves[i - 1].name:                    
                        #xValue is always in first column (time)
                        tempParsedCurves[i - 1].xUnitData.values.append(float(parts[0]))
                        #yValue depends on the index of the current curve
                        tempParsedCurves[i - 1].yUnitData.values.append(float(parts[j + 1]))
                else:
                    isReading = False

在第一个for循环中创建曲线后,它们将被添加到tempParsedCurves中,然后在循环可能的曲线时使用tempParsedCurves来添加值

当一个值被确定为属于一条曲线时,它通过首先加上x值,然后再加上y值而被添加到正确的曲线(tempParseCurves[i-1])。我很确定这是正确的,因为下面的打印放在最里面的if case中,显示了正确的曲线名称和值:

    print("to curve " + tempParsedCurves[i - 1].name + ", appending x: " + str(float(parts[0])) + ", y: " + str(float(parts[j + 1])))

在这一点上,一切似乎都很好,值被添加到各自的曲线中但是,如果在解析完成后尝试循环“tempParsedCurves”,则所有曲线都具有相同的x和y值

这可能是因为我在实际应该克隆clone.clone/deepclone时意外引用了其中一个对象的同一个实例吗


Tags: thetextinforcurrentfloat曲线parts
1条回答
网友
1楼 · 发布于 2024-10-03 19:29:59

没有一些示例数据很难进行故障排除,但是我认为这可能是因为您在以下两行代码中引用的是“parts”而不是“part”:

tempParsedCurves[i - 1].xUnitData.values.append(float(parts[0]))
                    #yValue depends on the index of the current curve
                    tempParsedCurves[i - 1].yUnitData.values.append(float(parts[j + 1]))

相关问题 更多 >