【python】 一次读两行文本

python 每次读两行文本

  1. 方法一:enumerate()函数获得行号,用行号取余;
import time
import itertools

start1=time.perf_counter()

List1=[]
path = r"C:\Users\xx.csv"

with open(path) as f:
	for lineID, line in enumerate(f):
		if lineID % 2 == 0:
			List1.append(line)
		if lineID % 2 == 1:
			List1.append(line)

f.close()
        

print("time used= ", time.perf_counter()-start1)
  1. 方法二
  • itertools.zip_longest(*iterables, fillvalue=None)

    Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.
    聚合多个迭代对象,长度为最长的对象。

start2 = time.perf_counter()

List2 = []
with open(path) as f:
    for line1, line2 in itertools.zip_longest(*[f]*2):
    	List2.append(line1)
        List2.append(line2)
f.close()

print("time used= ",time.perf_counter() -start2)
  1. 方法三:
start3 = time.perf_counter()

List3 = []
with open(path) as f:
    while True:
        line1=f.readline()
        line2=f.readline()
        if not line2:
            break
        List3.append(line2)
f.close()

print("time used= ", time.perf_counter() - start3)

参考:

https://blog.csdn.net/yihang___/article/details/79435602
https://docs.python.org/3.8/library/itertools.html?highlight=itertools%20zip_longest#itertools.zip_longest

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值