Skip to main content
 首页 » 编程设计

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

2025年05月04日17shanyou

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

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