我有一些问题避免我的代码重复自己,就像标题所说的,当我从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”读我怎么改,以防止重复的代码?
为什么你必须将所有的信息插入这些变量?您可以直接从'fundamenta_list'访问数据。 – Moyote
我从变量创建对象。当时这些数字是3,但在未来,这个列表会变得更大,因此我认为需要更加标准化的方法! – Jurkka
我不确定你的意思是“我的问题是,如果有更聪明的方法来循环功能”。你的示例代码中没有任何功能。下面的答案是否对你有帮助? – Moyote