开发者

Writing data from python list?

开发者 https://www.devze.com 2023-02-15 01:48 出处:网络
I have three list A,B and C. I want to write the contents of the list to the file like this: A[1] B[1] C[1]

I have three list A,B and C. I want to write the contents of the list to the file like this: A[1] B[1] C[1]

开发者_运维问答

A[2] B[2] C[2] . . .


Take a look at using zip. With zip you get a list of tuples, the tuples being the ith item of each list. As a bonus, the list of tuples is truncated to the shortest list of the three:

myComboList = zip(A, B, C)

Then you can always write the things in the order you'd like them without fear that one list may be shorter/longer than any of the others.


I assume that the lengths of all lists are the same,

assert len(A) == len(B) == len(C)
for a, b, c in zip(A, B, C):
    print a, b, c    # replace with file write


If your lists are long, itertools.izip() will probably be your friend. File object .writelines() can consume the list, or you can insert a yield construct in between to do the formatting.

def format(seq):
  for l in seq:
    yield "%s %s %s" % l
f.writelines(format(itertools.izip(A, B, C)))


Taking idea of itertools.izip() from Bittrance ,

plus the fact that a built-in function format() already exists :

import itertools

A = ['arez','hgjkhg','jhdfg','uhireug']
B = ['aaa','bbb','cccc','ddd']
C = ['XXXX','YYYY','ZZZZ','WWWWW']

with open('zorgl.txt','w') as f:
    f.writelines("[{0}] [{1}] [{2}]\n".format(*tu)
                 for tu in itertools.izip(A, B, C))

result in the file

[arez] [aaa] [XXXX]
[hgjkhg] [bbb] [YYYY]
[jhdfg] [cccc] [ZZZZ]
[uhireug] [ddd] [WWWWW]

And a revelation happened to me:

I had never realized that writelines() writes a sequence of strings, which can be an iterable, while write() writes only one string

Until now I was doing this kind of thing:

f.write('\n'.join(sequentia))

to write in a file.

But '\n'.join(sequentia) is an object that is created before being written in one time. I believe.

Comparatively, writelines() can receive an iterable, then the writing of lines can be done one line at a time. This allows to write progressively a big quantity of data in a file, while it could be harder to write the total amount of data in only one chunk at one time.

Am I right ?

The only little defect of writelines() is that it writes the strings as they are, without adding a newline.

So writelines(sequentz) writes the same as write(''.join(sequentz)) . Only write('\n'.join(sequentz)) adds a newline between elements

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号