我经常遇到从文件或任何地方提取信息的情况,然后必须通过几个步骤将数据按到最终所需的表格。例如:
def insight_pull(file):
with open(file) as in_f:
lines = in_f.readlines()
dirty = [line.split(' ') for line in lines]
clean = [i[1] for i in dirty]
cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]
cleanest = [i[0].split() + i[1].split() for i in cleaner]
with open("Output_File.txt", "w") as out_f:
out_f.writelines(' '.join(i) + '\n' for i in cleanest)
根据上面的例子:
# Pull raw data from file splitting on ' '.
dirty = [line.split(' ') for line in lines]
# Select every 2nd element from each nested list.
clean = [i[1] for i in dirty]
# Couple every 2nd element with it's predecessor into a new list.
cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]
# Split each entry in cleaner into the final formatted list.
cleanest = [i[0].split() + i[1].split() for i in cleaner]
因为我无法将所有编辑放入一行或循环(因为每次编辑都依赖于之前的编辑),有没有更好的方法来构建这样的代码?
如果问题有点含糊,请道歉。任何意见都非常感谢。
答案 0 :(得分:2)
您不想创建多个列表是正确的。你的列表理解创建了一个全新的列表,浪费了内存,你正在遍历每个列表!
@ VPfB使用gererator的想法是一个很好的解决方案,如果您的代码中有其他地方可以重用生成器。如果您不需要重用生成器使用,生成器表达式。
生成器表达式是惰性的,就像生成器一样,所以当链接在一起时,就像这里一样,当调用writelines时,循环将在结束时计算一次。
def insight_pull(file):
with open(file) as in_f:
dirty = (line.split(' ') for line in in_f) # Combine with next
clean = (i[1] for i in dirty)
cleaner = (pair for pair in zip(clean,clean)) # Redundantly silly
cleanest = (i[0].split() + i[1].split() for i in cleaner)
# Don't build a single (possibily huge) string with join
with open("Output_File.txt", "w") as out_f:
out_f.writelines(' '.join(i) + '\n' for i in cleanest)
离开以上内容时,您可以更进一步:
def insight_pull(file):
with open(file) as in_f:
clean = (line.split(' ')[0] for line in in_f)
cleaner = zip(clean,clean)
cleanest = (i[0].split() + i[1].split() for i in cleaner)
with open("Output_File.txt", "w") as out_f:
for line in cleanest:
out_f.write(line + '\n')
答案 1 :(得分:1)
我假设您的示例中只有cleanest
列表对您有任何实际价值,其余的只是中间步骤,可以毫无顾虑地丢弃。
假设是这种情况,为什么不在每个中间步骤中重复使用相同的变量,这样你就不会在内存中保存多个列表?
def insight_pull(file):
with open(file) as in_f:
my_list = in_f.readlines()
my_list = [line.split(' ') for line in my_list]
my_list = [i[1] for i in my_list]
my_list = [[my_list[i],my_list[i + 1]] for i in range(0, len(my_list),2)]
my_list = [i[0].split() + i[1].split() for i in my_list]
with open("Output_File.txt", "w") as out_f:
out_f.writelines(' '.join(i) + '\n' for i in my_list)
答案 2 :(得分:1)
如果您在考虑性能方面,那么您正在寻找发电机。生成器很像列表,但是它们被懒惰地评估,这意味着每个元素只在需要时生成。例如,按照以下顺序,我实际上并没有创建3个完整列表,每个元素只评估一次。下面只是生成器的一个示例使用(据我所知,您的代码只是您遇到的问题的一个示例,而不是具体问题):
# All even values from 2-18
even = (i*2 for i in range(1, 10))
# Only those divisible by 3
multiples_of_3 = (val for val in even if val % 3 == 0)
# And finally, we want to evaluate the remaining values as hex
hexes = [hex(val) for val in multiples_of_3]
# output: ['0x6', '0xc', '0x12']
两个第一个表达式是生成器,最后一个只是列表推导。由于您没有创建中间列表,因此在执行大量步骤时会节省大量内存。请注意,生成器无法编入索引,并且只能评估一次(它们只是值的流)。
答案 3 :(得分:1)
为了达到目标,我建议管道处理。我发现了一篇文章,它表达了这项技术:generator pipelines。
这是我尝试将循环直接转换为管道。代码未经测试(因为我们没有要测试的数据)并且可能包含错误。
func名称中的前导f
代表过滤器。
def fromfile(name):
# see coments
with open(name) as in_f:
for line in in_f:
yield line
def fsplit(pp):
for line in pp:
yield line.split(' ')
def fitem1(pp):
for item in pp:
yield item[1]
def fpairs(pp):
# edited
for x in pp:
try:
yield [x, next(pp)]
except StopIteration:
break
def fcleanup(pp):
for i in pp:
yield i[0].split() + i[1].split()
pipeline = fcleanup(fpairs(fitem1(fsplit(fromfile(NAME)))))
output = list(pipeline)
对于实际使用情况,我会聚合前3个过滤器以及接下来的2个过滤器。