Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表保存到.txt文件中,每个值之间有行_Python_Python 3.x - Fatal编程技术网

Python 将列表保存到.txt文件中,每个值之间有行

Python 将列表保存到.txt文件中,每个值之间有行,python,python-3.x,Python,Python 3.x,所以我找到了这个答案(stackoverflow.com/questions/33686747/save-a-list-to-a-txt-file),这很好,但它没有告诉我如何在创建的文本文件中将值放在单独的行中 以下是我的代码(如果有帮助): 身高和体重=['James',73,1.82,'Peter',78,1.80,'Beth',65,1.53,'Mags',66,1.50,'Joy',62,1.34] 以open(“heightandweight.txt”、“w”)作为输出: 输出写入(

所以我找到了这个答案(stackoverflow.com/questions/33686747/save-a-list-to-a-txt-file),这很好,但它没有告诉我如何在创建的文本文件中将值放在单独的行中

以下是我的代码(如果有帮助):

身高和体重=['James',73,1.82,'Peter',78,1.80,'Beth',65,1.53,'Mags',66,1.50,'Joy',62,1.34]

以open(“heightandweight.txt”、“w”)作为输出:

输出写入(str(高度和重量))


您需要遍历列表,分别添加每一行,添加“\n”以表示您需要新行:

with open("heightandweight.txt", "w") as output:
    for i in heightandweight:
        output.write(str(i) + "\n")
给予

如果您想在同一行中添加一个名称及其身高和体重,那么事情会稍微复杂一些:

with open("heightandweight.txt", "w") as output:
    for i, name in enumerate(heightandweight, 0):
        if i % 3 == 0:
            output.write("%s %i %.2f\n" % (heightandweight[i], heightandweight[i+1], heightandweight[i+2]))
它使用
enumerate
获取整数值
i
,该整数值在for循环每次迭代时递增1。然后检查它是否是三的倍数,如果是,则使用。以下是输出:

James 73 1.82
Peter 78 1.80
Beth 65 1.53
Mags 66 1.50
Joy 62 1.34

这并不是最好的方法。你最好使用一个列表:
[['James',73,1.82],'Peter',78,1.80],'Beth',65,1.53],'Mags',66,1.50],'Joy',62,1.34]。

我知道我不应该留下感谢的评论,但是。。。非常感谢你!
James 73 1.82
Peter 78 1.80
Beth 65 1.53
Mags 66 1.50
Joy 62 1.34