使用python将列表打印到.txt文件中的表的有效方法

2024-05-29 11:38:33 发布

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

我想创建一个包含从列表创建的表的文本文件。但是,我不想做这样的事:

import string
print >> textfile, string.rjust(listname[0],3), string.rjust(listname[1],3),

下面的代码演示了我想做但不起作用的想法:

import string
listname = ['test1','test2','test3']
i=0
for i in range(0,3):
   print >> textfile, string.rjust(listname[i],5)

我希望输出结果与此完全相同:

test1   test2   test3

这正是我想做的,也是我脑子里的想法,但显然这行不通。

我使用了join()函数来很好地打印列表,但是我无法获得表的正确间距。

有什么想法吗?


Tags: 代码inimport列表forstringrangeprint
3条回答

你说它不工作是什么意思?

首先,rjust将在字符串中包含字符。看起来你想要一个8左右的rjust来获得你用"test1"这样的字符串寻找的间距。

其次,因为打印的末尾没有逗号,所以它会将每一个打印到一个新行上。你可能想要这样的东西:

print >> textfile, string.rjust(listname[i],8),

然后,在您退出循环后,您需要打印换行符:

print >> textfile

现在,我们在行的开头有一些空白,因为我们rjust是列表中的第一项。实际上,您可能需要这种行为,因为这样列就会排成一行,另一个选项是使用ljust


一些次要的风格建议:

  • i=0在这里什么也不做;它将被覆盖
  • for item in listname可能比你正在做的range更好。
  • 与其string.rjust,不如直接调用字符串本身的rjust,比如:listname[i].rjust(8)

如果你想熟练掌握join和列表理解,你可以:

print >> textfile, ' '.join(item.rjust(8) for item in listname)

这将对所有项执行rjust,然后用空格将它们连接起来(您也可以在这里使用空字符串)。

认为最有效的方法是使用.join方法生成字符串,然后对文件执行一次写操作。

如果我能正确理解这个问题,你就可以这么做。。。

>>> def print_table():
...     headers = ['One', 'Two', 'Three']
...     table = [['test1', 2, 3.0],
...             ['test4', 5, 6.0],
...             ['test7', 8, 9.0],
...             ]
...     print ''.join(column.rjust(10) for column in headers)
...     for row in table:
...         print ''.join(str(column).rjust(10) for column in row)
... 
>>> 
>>> print_table()
       One       Two     Three
     test1         2       3.0
     test4         5       6.0
     test7         8       9.0
>>> 

不需要string模块或整数索引到表中。

为了清楚起见,我已经按标准打印出来了,但你也可以同样容易地写入文件。

相关问题 更多 >

    热门问题