【问题标题】:Python write varying-length list to txt filePython将变长列表写入txt文件
【发布时间】:2018-01-05 15:11:27
【问题描述】:

我想将一个列表输出到一个带有格式的 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]))

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

【问题讨论】:

  • 解包列表:format(*a)

标签: python list format output


【解决方案1】:

只需使用mapjoin

a = [1,2,3]

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

【讨论】:

    【解决方案2】:

    正如评论中所说,您可以将unpacking your list 转换为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'
    

    通过这样做,您避免了必须通过其每个索引显式传递a。但这可以使用map()str.join() 更清洁:

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

    【讨论】:

    • 如果@downvoter 能解释他们的推理,我将不胜感激?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 2014-05-02
    • 2015-06-12
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多