怎么把python列表写入文件_Python将列表写入文本文件

1586010002-jmsa.png

I am using python format method to write a list of numbers into a text file. When the list length is fixed I can do:

a = [16,1,16,1]

myfile.write('{0},{1},{2},{3}'.format(*a) + "\n")

My question is how to use the format method when the size of list is not fixed. Is there any easy easy way of doing this? Rather than first create a string b, and then map a to b. I am not sure if I can use something like myfile.write('{all elements in a}'.format(*a) + "\n")

b=''

for i in range(len(a)):

if i<(len(a)-1):

b=b+'{'+ str(i) + '},'

else:

b=b+'{'+ str(i) + '}'

myfile.write(b.format(*a) + "\n")

解决方案

Use str.join:

>>> lis = [16,1,16,1]

>>> ','.join(str(x) for x in lis) + '\n'

'16,1,16,1\n'

>>> lis = range(10)

>>> ','.join(str(x) for x in lis) + '\n'

'0,1,2,3,4,5,6,7,8,9\n'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值