But is it possible to do the same in python?
是的,您可以:l1, l2 = [[],[]]
with open('in.txt', 'r') as f:
for i in f:
# will loudly fail if more than two columns on a line
left, right = i.split('\t')
l1.append(left)
l2.append(right)
print("\n".join(l1))
print("\n".join(l2))would it be faster?
不太可能,cut是一个针对这种处理进行了优化的C程序,python是一种通用语言,具有很大的灵活性,但不一定很快。在
不过,使用我编写的算法的唯一好处是,只读取一次文件,而使用cut,则可以读取两次。这可能会有不同。在
尽管我们需要进行一些基准测试才能达到100%。在
在我的笔记本电脑上有一个小小的基准,它的价值是:
^{pr2}$
与% time cut -d' ' -f1 file_of_606251_lines > /dev/null
cut -d' ' -f1 file_of_606251_lines > /dev/null 0.74s user 0.02s system 98% cpu 0.775 total
% time cut -d' ' -f2 file_of_606251_lines > /dev/null
cut -d' ' -f2 file_of_606251_lines > /dev/null 1.18s user 0.02s system 99% cpu 1.215 total
也就是1.990秒。在
所以python版本确实比预期的更快;-)