0

I have a text file where I want to write values from following three lists:

a = [1,2,3]
b = [4,3,2]
c = [7,8,9]

in format:

a-b
c

so the arrangement in text file would look like:

1-4   2-3   3-2  
7     8     9

I have tried following

for x,y,z in zip(a,b,c): ofile.write("p%s-%s\n%s\t" %(x,y,z))

But output in text file is arranged like this:

1-4
7     2-3
8     3-2
9

Any suggestions on how to return to first line and arrange text as needed would be appreciative.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ibe
  • 5,615
  • 7
  • 32
  • 45

1 Answers1

2

Zip a and b on their own, write that line, then write c on the next:

ofile.write('\t'.join(['{}-{}'.format(*pair) for pair in zip(a, b)]) + '\n')
ofile.write('\t'.join(map(str, c)) + '\n')

This uses str.join() to put tabs between the values on a line.

It'd be easier to use the csv module to take care of turning values into strings and to write tabs and line separators:

writer = csv.writer(ofile, delimiter='\t')
writer.writerow(['{}-{}'.format(*pair) for pair in zip(a b)])
writer.writerow(c)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Or replace `'{}-{}'.format(*pair)` with `'%s-%s' % pair`. – WKPlus May 12 '14 at 07:14
  • @WKPlus: sure, but I prefer to teach the more powerful and newer `str.format()` method. – Martijn Pieters May 12 '14 at 07:14
  • @MartijnPieters: One side question -- if I have another list 'd' which has 9 values and I want to place every 3 values from it underneath each column sequentially to get them in 3 rows. How to do it? – Ibe May 12 '14 at 08:14
  • @Ibe: [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/q/312443); split into chunks, pass chunks to `writerows()`. – Martijn Pieters May 12 '14 at 15:48