Python将变长列表写入txt文件

Tom*_*Tom 2 python format list output

我想将列表输出到具有格式的txt文件中。但列表长度会不时发生变化。

代码是这样的:

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]))
Run Code Online (Sandbox Code Playgroud)

我想知道应该如何修改这段代码,以便该代码可以适用于不同的列表长度?

小智 5

只需使用mapjoin

a = [1,2,3]

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