Python初学者在这里尝试学习如何使我的代码更加精简。很抱歉这个问题很长,我不知道你们需要多少信息才能帮助我。
我有一段代码完全符合我的需要,但我觉得它应该更紧凑。
基本上我的代码需要一个文件,乘以一个数字,然后每次运行代码时将文件写入不同的目录。
为了让代码做我想做的事,我基本上必须重复代码 9x(乘数列表中的每个项目一次),因为我希望每次都将结果写入不同的目录。
有没有办法压缩这段代码?代码应采用第 0 个索引并写入 FileLocation1。然后取第一个索引并写入 FileLocation2。这可能是使用 for 循环的问题,但我不知道把它放在哪里:(
代码如下:
#Identifying path where the file is that I want to multiply
path = 'C:\\DirectoryIWantToTakeFileFrom'
#Define the multipliers in the list below
multipliers = [0.01, 0.1, 0.25, 0.5, 1, 1.5, 1.7, 1.85, 2]
all_data0 = []
with open(path, 'r') as file_handler:
for multiplier in multipliers:
for line in file_handler.readlines():
if line.strip():
each_line_data = line.split()
old_debiet = each_line_data[-3]
new_debiet = float(old_debiet) * multipliers[0]
each_line_data[-3] = str(new_debiet)
new_each_line_data = ' '.join(each_line_data)
all_data0.append(new_each_line_data)
with open('C:\\WriteLocation1', 'w') as file_handler:
for item in all_data0:
file_handler.write("{}\n".format(item))
#Now I proceed to execute exactly the same code but I store the data in a different list (all_data1) and I change the writing directory
all_data1 = []
with open(path, 'r') as file_handler:
for multiplier in multipliers:
for line in file_handler.readlines():
if line.strip():
each_line_data = line.split()
old_debiet = each_line_data[-3]
new_debiet = float(old_debiet) * multipliers[1]
each_line_data[-3] = str(new_debiet)
new_each_line_data = ' '.join(each_line_data)
all_data1.append(new_each_line_data)
with open('C:\\WriteLocation2', 'w') as file_handler:
for item in all_data1:
file_handler.write("{}\n".format(item))
#And now I do this 7 more times, for WriteLocation3, 4, 5, 6, 7, 8 and 9.
米琪卡哇伊
守着一只汪
相关分类