Printing alternate lines using python

I have a text file like

1
2
3
4
5
6
7
8
9
10

... etc.

How to write a program to print the first two lines, then skip 3, and then print 2 lines (this is a pattern.)

I'm a complete noob. Any help would be appreciated.

thank.

+3
source share
6 answers

Based on the listing of the lines and assuming a 5-point loop (display the first two elements, skip the following three elements):

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

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

, , . file.readlines() . , itertools.compress() , itertools.cycle(). , , .

+2

, , modulo. - :

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

, .

+1

:

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

: -)

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

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

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

@pynator itertools module, , ifilter - imap.

z , file("myfile.txt"). 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
>>> 
0

Source: https://habr.com/ru/post/1795403/


All Articles