简体   繁体   English

Python将变长列表写入txt文件

[英]Python write varying-length list to txt file

I want to output a list into a txt file with format. 我想将列表输出到带格式的txt文件中。 But the list length will change from time to time. 但是列表长度会不时变化。

The code is like this: 代码是这样的:

a = [1, 2, 3] #**but this could also be: a = [1, 2, 3, 6, 9] or [1, 90]**
with open('node.k','w') as file:
    file.write(((len(a)-1)*'{},'+'{}\n').format(a[0],a[1],a[2]))

I was wondering how should I modify this code so that this code can work for different list length? 我想知道如何修改此代码,以便此代码可以用于不同的列表长度?

As said in the comment, you can do this by unpacking your list into str.format() : 如评论中所述,您可以通过将列表解 str.format()str.format()来完成此操作:

>>> a = [1, 2, 3]
>>> ((len(a)-1)*'{},'+'{}\n').format(*a)
'1,2,3\n'
>>> a = [1, 2, 3, 7, 60]
>>> ((len(a)-1)*'{},'+'{}\n').format(*a)
'1,2,3,7,60\n'

By doing this, you avoid having to explicitly pass in a by each of its indexes. 这样一来,您就不必在明确地传递a由它的每一个指标。 But this can be done cleaner using map() and str.join() : 但是使用map()str.join()可以做得更干净:

>>> a = [1, 2, 3]
>>> ','.join(map(str, a)) + '\n'
'1,2,3\n'

Just use map and join : 只需使用mapjoin

a = [1,2,3]

with open('node.k','w') as file:
    file.write(','.join(map(str,a))+'\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM