当我从txt文件导入数据时,我遇到了一些问题,就像标题所说的那样,避免代码重复自己。我的问题是,是否有更聪明的方法来循环这个函数。一般来说,我对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“中读取时,我该如何更改以防止代码重复?
发布于 2017-08-10 20:14:32
在我看来,您的输入文件的每个记录都是一个4行的块,因此依次是namerow、sol、pe、ps,您将创建接受这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的答案中所示。
https://stackoverflow.com/questions/45612535
复制相似问题