gpt4 book ai didi

产生文本文件交替行的 Pythonic 方法

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:34 26 4
gpt4 key购买 nike

我有一个文本文件如下,我想生成奇数/偶数行:

this is a blah 
I don't care,
whatever foo bar
ahaha

我已经尝试检查枚举索引的奇数/偶数,但是在文本文件中生成交替行的 pythonic 方法是什么?我试过:

text = "this is a blah \n I don't care,\nwhatever foo bar\nahaha"
with open('test.txt', 'w') as fout:
for i in text.split('\n'):
print>>fout, i

def yield_alt(infile, option='odd'):
with open(infile,'r') as fin:
for i,j in enumerate(fin):
if option=='odd':
if i+1 & 0x1:
yield j
elif option=='even':
if i & 0x1:
yield j

for i in yield_alt('test.txt'):
print i

[输出]:

this is a blah 

whatever foo bar

最后,i & 0x1 是什么意思?我知道它会检查偶数,还有其他检查偶数的方法吗?

最佳答案

另一种方法是使用 iterools.islice 对文件对象进行切片:

>>> from itertools import islice
>>> def yield_alt(f, option='odd'):
if option == 'odd':
return islice(f, 0, None, 2)
return islice(f, 1, None, 2)
...
>>> with open('abc1') as f:
for line in yield_alt(f):
print line,
...
this is a blah
whatever foo bar

>>> with open('abc1') as f:
for line in yield_alt(f, 'even'):
print line,
...
I don't care,
ahaha

关于产生文本文件交替行的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21393564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com