带有for循环和列表的Python语法,导出为文本fi

2024-05-18 12:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Joining List has integer values with python

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

示例:文本文件中应该包含什么 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()

Tags: 列表forwith语法数字integerlisthas
3条回答

如果要使用range()生成数字列表,则可以使用以下命令:

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

map(str, iterable)将对这个iterable对象中的所有元素应用str()。在

^{}用于用context manager定义的方法包装块的执行,这允许封装通用的try...except...finally使用模式以方便重用。在这种情况下,它将始终关闭f。使用它而不是手动调用f.close()是一个很好的实践。在

您必须将整数列表转换为stringsmap()上的列表,以使其可连接。在

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

试试这个:

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

相关问题 更多 >

    热门问题