2017-08-10 56 views
0

我有一些问题避免我的代码重复自己,就像标题所说的,当我从txt文件导入数据时。我的问题是,如果有更聪明的方式来循环功能。一般来说,我仍然对Python非常陌生,所以我对这方面的知识还不够。从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”读我怎么改,以防止重复的代码?

+0

为什么你必须将所有的信息插入这些变量?您可以直接从'fundamenta_list'访问数据。 – Moyote

+0

我从变量创建对象。当时这些数字是3,但在未来,这个列表会变得更大,因此我认为需要更加标准化的方法! – Jurkka

+0

我不确定你的意思是“我的问题是,如果有更聪明的方法来循环功能”。你的示例代码中没有任何功能。下面的答案是否对你有帮助? – Moyote

回答

0

在我看来,你的输入文件中有记录每个为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的功能回答。

0

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

你可以这样做:

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") 
+0

这看起来很有前途,是的,这就是我的意思!对不起,如果我不清楚。我会马上试试这个! – Jurkka

+0

@Jurkka,有帮助吗? – Moyote

+0

我想用代码来改进的东西是诸如“namerow_1”等变量,因此代码可以读取无限长的txt文件并按照相同的模式创建对象。所以我猜想需要某种循环来解决这个问题,那就是我面临的更大的问题。你有什么想法如何解决这个问题? – Jurkka