【问题标题】:How to print variable length lists as columns in python?如何在python中将可变长度列表打印为列?
【发布时间】:2015-03-16 15:27:07
【问题描述】:

我需要一种方法来打印多个不同长度的列表,作为相邻的列分隔的制表符,并且空单元格保持为空或包含一些填充字符(例如“-”)。

到目前为止,尝试的方法对于不同长度的列表都不起作用,并且 numpy 并没有像我预期的那样起作用。

总结一下:

listname = [[1,2,3],[4,5,6,7,8],[9,10,11,12]]

打印在 .txt 文件中:

1    4    9
2    5    10
3    6    11
-    7    12
-    8    -

【问题讨论】:

标签: python list multiple-columns


【解决方案1】:

您可以使用itertools.izip_longest。要填充较长序列中的None 空格,您可以使用fillvalue(感谢@szxk):

>>> import itertools
>>> listname = [[1,2,3],[4,5,6,7,8],[9,10,11,12]]
>>> for x in itertools.izip_longest(*listname, fillvalue="-"):
...     print '\t'.join([str(e) for e in x])
... 
1   4   9
2   5   10
3   6   11
-   7   12
-   8   -

【讨论】:

  • 需要注意的是 izip_longest 接受一个填充值作为参数,所以你可以写成itertools.izip_longest(*listname, fillvalue="-")
  • @ReutSharabani 为什么需要转换为字符串才能正常工作?排除字符串转换会引发错误...
  • 如果你在谈论这条线:print '\t'.join([str(e) for e in x]) 这是必要的,因为你有一个ints 的列表,而str.joinstrs 的列表中运行。引用:返回一个字符串,它是可迭代迭代中的 字符串 的串联。 docs.python.org/2/library/stdtypes.html#str.join
【解决方案2】:

在这种情况下,您可以使用zip 函数,这对于itertools.izip 的小列表更有效

listname = [[1,2,3],[4,5,6,7,8],[9,10,11,12]]

with open('a.txt',w) as f: 
   for tup in zip(*listname) :
          f.write('\t'.join(map(str,tup))

基准测试:

~$ python -m timeit "import itertools;listname = [[1,2,3],[4,5,6,7,8],[9,10,11,12]];itertools.izip_longest(*listname)"
1000000 loops, best of 3: 1.13 usec per loop
~$ python -m timeit "listname = [[1,2,3],[4,5,6,7,8],[9,10,11,12]];zip(*listname)"
1000000 loops, best of 3: 0.67 usec per loop

【讨论】:

    【解决方案3】:

    pandas怎么样:

    In [38]: listname = [[1,2,3],[4,5,6,7,8],[9,10,11,12]]
    
    In [39]: import pandas as pd
    
    In [40]: df = pd.DataFrame(listname, dtype=object)
    
    In [41]: df.T
    Out[41]: 
          0  1     2
    0     1  4     9
    1     2  5    10
    2     3  6    11
    3  None  7    12
    4  None  8  None
    
    [5 rows x 3 columns]
    
    In [42]: df.T.to_csv("my_file.txt", index=False, header=False, sep="\t", na_rep="-")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 2022-10-31
      • 1970-01-01
      • 2015-12-23
      • 2021-10-07
      • 2021-05-04
      • 2021-11-12
      相关资源
      最近更新 更多