简体   繁体   English

使用python打印备用线

[英]Printing alternate lines using python

I have a text file like 我有一个像文本文件

1
2
3
4
5
6
7
8
9
10

... and so on. ... 等等。

How do I write a program to print the first 2 lines then skip 3 then print 2 lines (that's the pattern.) 如何编写程序来打印前2行然后跳过3然后打印2行(这就是模式。)

I'm a complete noob. 我是一个完整的菜鸟。
Any help will be appreciated. 任何帮助将不胜感激。

thanks. 谢谢。

Based on line enumeration and assuming a 5-item cycle (display first two items, skip next three items): 基于行枚举并假设一个5项循环(显示前两项,跳过下面三项):

for i, line in enumerate(file('myfile.txt')):

   if i % 5 in (0, 1):
       print line

I don't know if there's a pattern for this, really. 我不知道是否有这种模式,真的。 You could just file.readlines() the entire thing and use array slicing. 你可以只是file.readlines()整个事情并使用数组切片。 If you're concerned about memory consumption, iterate over the file handle using itertools.compress() on a pattern generated by itertools.cycle() . 如果你担心内存消耗,使用迭代文件句柄itertools.compress()对生成的图案itertools.cycle() Or, you know, just write a loop or list comprehension. 或者,你知道,只需写一个循环或列表理解。

The best that I can come up with is to use the modulo operator. 我能想到的最好的是使用模运算符。 Something like this: 像这样的东西:

f = open('filename.txt', 'r')
for index, line in enumerate(f.readlines()):
    if index%5 <= 1:
       print(line)

This should produce the pattern you are looking for. 这应该产生你正在寻找的模式。

Since others beat me to the answer here's the one line version: 由于其他人在这里击败我的答案是一行版本:

print list(line for lineNum, line in enumerate(open("test.txt", "r")) if lineNum % 5 in (0, 1))

:-) :-)

with open(filename) as f:
    print ''.join( f.readline() for i in xrange(7) if i in (0,1,5,6))

or 要么

with open(filename) as f:
    print ''.join( f.readline() for i in '1100011' if i=='1')

or 要么

with open(filename) as f:
    print ''.join( i*f.readline() for i in (1,1,0,0,0,1,1))

Building on @pynator's answer, and using the itertools module , here is the same solution as a ifilter - imap combination. 基于@pynator的答案,并使用itertools模块 ,这里是与ifilter - imap组合相同的解决方案。

z is an iterable, like file("myfile.txt") . z是一个可迭代的file("myfile.txt") imap is used to pick the original data item from an enumerated pair. imap用于从枚举对中选择原始数据项。

>>> from itertools import ifilter, imap
>>> result = imap(lambda x: x[1], ifilter(lambda x: x[0]%5 in (0,1), enumerate(z)))
>>> for i in result: print i
... 
line 1
line 2
line 6
line 7
line 11
line 12
line 16
line 17
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM