我有一个如下文本文件,我想要产生奇数/偶数行:
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
[OUT]:
this is a blah
whatever foo bar
最后, i & 0x1
是什么意思?我知道它检查偶数int,还有其他检查偶数的方法吗?
答案 0 :(得分:3)
i & 0x1
对最后一位进行位掩码,以检查i
是偶数还是奇数。我一般i % 2
因为我感觉更清楚,但不确定哪一个有更好的表现。
修改:timeit
和dis
:
>>> timeit(lambda:5 & 0x1, number=1000000)
0.10139431793770104
>>> timeit(lambda:5 % 2, number=1000000)
0.10143369172932282
>>> dis.dis(lambda: 5 & 0x1)
1 0 LOAD_CONST 2 (1)
3 RETURN_VALUE
>>> dis.dis(lambda: 5 % 2)
1 0 LOAD_CONST 2 (1)
3 RETURN_VALUE
它们几乎完全相同。无论哪个更清楚,你应该使用它。
答案 1 :(得分:3)
另一种方法是使用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
答案 2 :(得分:0)
islice
可能是您的最佳选择,但为了完整起见,我将使用next
添加另一个选项,以跳过您不想要的行。
def yield_alt(filename, option='odd'):
with open(filename) as ifile:
if option.lower() == 'odd':
# Skip first line
next(ifile)
for line in ifile:
yield line
# Skip next line
next(ifile)