Join every 3 lines together Python -


i have list stored in variable example:

  • 01/01/2015
  • 13:22
  • steak
  • 01/02/2015
  • 13:23
  • fries
  • 01/03/2015
  • 13:23
  • salad

i have variable z holds information.

i want join every 3 lines output date + time + order in 1 line. tried below puts 3 letters on each line rather 3 lines

threelines = range(0,len(z),3) num, line in enumerate(z):     if num in threelines:         print ' '.join(z[num:num+3]) 

any appreciated!

you not need use index, , can write explicit code like:

lines_iter = iter(z.splitlines())  # if z file, lines_iter = z works # itertools.izip() usable, too, low memory footprint: date_time_order in zip(lines_iter, lines_iter, lines_iter):     print " ".join(date_time_order)  # "<date> <time> <order>" 

this has advantage of giving legible variable names, , of working if z iterator (like file): there no need know number of lines in advance, , method uses little memory.

the way works comes specifics of how zip() works: it builds tuples of elements, getting next element of each of arguments in turn. thus, first returns first, second, , third element of lines_iter, etc.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -