0

I have a list of lists called sorted_lists

I'm using this to write them into a txt file. Now the thing is, this line below prints ALL the lists. I'm trying to figure it out how to print only first n (n = any number), for example first 10 lists.

f.write ("\n".join("\t".join (row) for row in sorted_lists)+"\n")
user1509923
  • 193
  • 1
  • 3
  • 13

4 Answers4

2

Try the following:

f.write ("\n".join("\t".join (row) for row in sorted_lists[0:N])+"\n")

where N is the number of the first N lists you want to print.

sorted_lists[0:N] will catch the first N lists (counting from 0 to N-1, there are N lists; list[N] is excluded). You could also write sorted_lists[:N] which implicitly means that it will start from the first item of the list (item 0). They are the same, the latter may be considered more elegant.

PALEN
  • 2,784
  • 2
  • 23
  • 24
1

f.write ('\n'.join('\t'.join(row) for row in sorted_lists[:n+1])+'\n')

where n is the number of lists.

Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114
1

Why not simplify this code and use the right tools:

from itertools import islice
import csv

first10 = islice(sorted_lists, 10)
with open('output.tab', 'wb') as fout:
    tabout = csv.writer(fout, delimiter='\t')
    tabout.writerows(first10)
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

You should read up on the python slicing features.

If you want to look at only the first 10 entires of sorted_lists, you could do sorted_lists[0:10].

Community
  • 1
  • 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173