【问题标题】:Python syntax with for loop and lists, exporting to text file [duplicate]带有for循环和列表的Python语法,导出到文本文件[重复]
【发布时间】:2012-09-29 10:48:20
【问题描述】:

可能重复:
Joining List has integer values with python

我在 python 中遇到了 for 循环和列表的语法问题。我正在尝试导出已导出到以空格分隔的文本文件的数字列表。

示例:文本文件中应包含的内容 0 5 10 15 20

我正在使用的代码如下,任何想法如何解决这个问题。

f = open("test.txt", "w")
mylist=[]
for i in range(0,20+1, 5):      
    mylist.append(i)
    f.writelines(mylist)

f.close()

【问题讨论】:

    标签: python for-loop append


    【解决方案1】:

    如果你想使用range() 来生成你的号码列表,那么你可以使用这个:

    mylist = map(str, range(0, 20 + 1, 5))
    with open("test.txt", "w") as f:
        f.writelines(' '.join(mylist))
    

    map(str, iterable)str() 应用于此可迭代对象中的所有元素。

    with 用于使用context manager 定义的方法包装块的执行,这允许封装常见的try...except...finally 使用模式以方便重用。在这种情况下,它会始终关闭f。使用它而不是手动调用f.close() 是一个好习惯。

    【讨论】:

    • @RickT 很高兴为您提供帮助 :) 您也可以阅读链接文档中的 withmap,因为它们是非常有用的常用功能。
    【解决方案2】:

    试试这个:

    mylist = range(0,20+1,5)
    f = open("test.txt", "w")
    f.writelines(' '.join(map(str, mylist)))
    f.close()
    

    【讨论】:

    • 我收到一个错误文件第 3 行,在 f.writelines(' '.join(mylist)) TypeError: sequence item 0: expected string, int found
    • 试试编辑后的版本,你得把整数转成字符串。
    • 这对猫的剥皮方法也很有效。 :-)
    【解决方案3】:

    您必须将整数列表转换为字符串列表map() 以使其可连接。

    mylist = range(0,20+1,5)
    f = open("test.txt", "w")
    f.writelines(' '.join(map(str, mylist)))
    f.close()
    

    另见Joining List has Integer values with python

    【讨论】:

      【解决方案4】:
      >>> with open('test.txt', 'w') as f:
      ...     f.write(' '.join((str(n) for n in xrange(0, 21, 5))))
      

      【讨论】:

        猜你喜欢
        • 2021-12-23
        • 2016-05-29
        • 1970-01-01
        • 2013-07-30
        • 1970-01-01
        • 1970-01-01
        • 2013-01-25
        • 2021-04-08
        • 1970-01-01
        相关资源
        最近更新 更多