将输出值保存在python列的txt文件中 [英] save output values in txt file in columns python

查看:963
本文介绍了将输出值保存在python列的txt文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入值给出相应的输出值为:

My input value gives corresponding output values as;

my_list = []
for i in range(1,10):
     system = i,i+2*i
     my_list.append(system)
     print(my_list)

[(1, 3)]

[(1, 3), (2, 6)]

[(1, 3), (2, 6), (3, 9)]

[(1, 3), (2, 6), (3, 9), (4, 12)]

我希望输出存储在2列中;其中 1,2,3 是第一列元素,第二列是 3,6,9

I want output stored in 2 columns; where 1,2,3is first column elements and 3,6,9 for 2nd column.

(1 3)
(2 6)
(3 9)

等......然后将这些值存储在文本文件中。对于文本文件,是否可以生成文本文件作为脚本的一部分?谢谢

so on... and then write store these values in text file. For text file, is it possible to generate text file as a part of script? Thanks

推荐答案

你需要保存相同的 my_list 元素索引 i-1 (您的范围从1开始):

you need to save the element of my_list that has equal index with i-1 (your range began at 1):

my_list=[] 
with open ('new.txt','w') as f:
 for i in range(1,10):
     system = i,i+2*i
     my_list.append(system)
     print(my_list)
     f.write(str(my_list[i-1])+'\n')

输出:

(1, 3)
(2, 6)
(3, 9)
(4, 12)
(5, 15)
(6, 18)
(7, 21)
(8, 24)
(9, 27)

也如评论中所说,您不需要 my_list 您可以使用以下代码执行此操作:

also as says in comments you don't need my_list you can do it with following code :

with open ('new.txt','w') as f:
 for i in range(1,10):
     system = i,i+2*i
     f.write(str(system)+'\n')

这篇关于将输出值保存在python列的txt文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆