首页 > 解决方案 > 将文件中的行放入多个变量中会产生奇怪的不一致

问题描述

在我尝试解释这一点之前,这是我目前正在使用的代码:

currentLine = 1
try:
    with open(filename, 'r') as f:
        for line in f:
            if currentLine == 1:
                tempName = line
            if currentLine == 2:
                tempColour = line
            if currentLine == 3:
                tempAge = line
            if currentLine == 4:
                tempWeight = line
                currentLine = 1
                tempSheep = Sheep(tempName, tempColour, tempAge, tempWeight)
                sheepList.append(tempSheep)
            currentLine = currentLine + 1
except:
    print("file is in an invalid format")
    continue
else:
    break

代码的目标是从文件中读取 4 行(名称、颜色、年龄和体重)并将它们放入 Sheep 对象中。这需要循环完成,因为每个文件有 2 到 10 只羊。该代码主要工作,因为它读取行并将它们放入类中,但它没有读取正确的行。当我打印出所有的羊时,每只羊的名字都一样,“bob”,这是文件中第一只羊的名字,也是第一行。除此之外,它确实有效,但它完全忽略了 name 变量,只是将 bob 放入其中。我最终得到了这群名叫鲍勃的羊。

例如,示例输出如下所示:

Name: bob
Colour: blue
age: 5
weight: 50

name: bob
Colour: tina
age: red
Weight: 7

name: bob
colour: 75
age: shirley
Weight: green

如果它不明显,它会通过忽略名称来抵消一切。我希望这已经解释得足够好,如果您需要进一步的解释,我可以尝试放入更多示例。

为什么我的程序不好?

标签: pythonfileline

解决方案


        if currentLine == 4:
            tempWeight = line
            currentLine = 1
            tempSheep = Sheep(tempName, tempColour, tempAge, tempWeight)
            sheepList.append(tempSheep)
        currentLine = currentLine + 1

当此if块执行时,它最初设置currentLine为 1。然后currentLine = currentLine + 1执行,将其设置为 2。这意味着,当您再次到达循环顶部时,if currentLine == 1:检查将永远不会成功。

尝试设置currentLine为零。

        if currentLine == 4:
            tempWeight = line
            currentLine = 0
            tempSheep = Sheep(tempName, tempColour, tempAge, tempWeight)
            sheepList.append(tempSheep)
        currentLine = currentLine + 1

...但是您最好完全跳过 if 块。如果您的每条记录正好有四行长,您可以使用如何将列表拆分为大小均匀的块?. 然后,您可以通过参数解包将数据传递给 Sheep 构造函数。

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

with open(filename) as f:
    lines = [line.strip() for line in f]

sheepList = []
for group in chunks(lines, 4):
    sheepList.append(Sheep(*group))

推荐阅读