从 txt-file - Python 排序信息时重复代码

Repeating code when sorting information from a txt-file - Python

当我从 txt-file 导入数据时,我在避免我的代码重复自身方面遇到了一些问题,就像标题所说的那样。我的问题是,是否有更聪明的方法来循环函数。总的来说,我对 python 还是很陌生,所以我在这方面的知识并不丰富。

我使用的代码如下

with open("fundamenta.txt") as fundamenta:
    fundamenta_list = []
    for row in fundamenta:
        info_1 = row.strip()
        fundamenta_list.append(info_1)

namerow_1 = fundamenta_list[1]
sol_1 = fundamenta_list[2]
pe_1 = fundamenta_list[3]
ps_1 = fundamenta_list[4]
namerow_2 = fundamenta_list[5]
sol_2 = fundamenta_list[6]
pe_2 = fundamenta_list[7]
ps_2 = fundamenta_list[8]
namerow_3 = fundamenta_list[9]
sol_3 = fundamenta_list[10]
pe_3 = fundamenta_list[11]
ps_3 = fundamenta_list[12]

那么当代码从 "fundamenta_list" 读取时,我该如何更改以防止代码重复?

如果我对你的问题的理解正确,你可能想从你的代码中创建一个函数,这样你就可以避免重复相同的代码。

你可以这样做:

def read_file_and_save_to_list(file_name):
    with open(file_name) as f:
    list_to_return = []
    for row in f:
        list_to_return.append(row.strip())
    return list_to_return

然后你可以这样调用函数:

fundamenta_list = read_file_and_save_to_list("fundamenta.txt")

在我看来,您的输入文件的每条记录都是 4 行的块,因此依次是 namerowsolpeps ,您将创建包含这 4 个字段的对象。假设您的对象名为 MyObject,您可以执行以下操作:

with open("test.data") as f:
    objects = []
    while f:
        try:
            (namerow, sol, pe, ps) = next(f).strip(), next(f).strip(), next(f).strip(), next(f).strip()
            objects.append(MyObject(namerow, sol, pe, ps))
        except:
            break

然后您可以访问您的对象 objects[0]

您甚至可以将其变成返回对象列表的函数,就像 Moyote 的回答中那样。