Python: Write two lists into two column text file

后端 未结 6 733
我寻月下人不归
我寻月下人不归 2020-12-13 07:23

Say I have two lists: a=[1,2,3] b=[4,5,6] I want to write them into a text file such that I obtain a two column text file:



        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 07:52

    Simply zip the list, and write them to a csv file with tab as the delimiter:

    >>> a=[1,2,3]
    >>> b=[4,5,6]
    >>> zip(a,b)
    [(1, 4), (2, 5), (3, 6)]
    >>> import csv
    >>> with open('text.csv', 'w') as f:
    ...    writer = csv.writer(f, delimiter='\t')
    ...    writer.writerows(zip(a,b))
    ...
    >>> quit()
    $ cat text.csv
    1       4
    2       5
    3       6
    

提交回复
热议问题