简体   繁体   English

如何在python中将可变长度列表打印为列?

[英]How to print variable length lists as columns in python?

I need a way to print several lists of varying lengths as columns next to each other tab delimited and with the empty cells remaining empty or containing some fill character (eg "-"). 我需要一种方法来打印多个不同长度的列表,这些列以彼此相邻的制表符分隔的列为单位,并且空单元格保持为空或包含一些填充字符(例如“-”)。

The methods attempted so far have not worked for lists of varying lengths and numpy has not been working as I expected it. 到目前为止,尝试的方法不适用于各种长度的列表,并且numpy未能按我预期的那样工作。

To summarize: 总结一下:

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

printed as such in a .txt file: 在.txt文件中打印为:

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

You can use itertools.izip_longest . 您可以使用itertools.izip_longest To fill the None spaces in the longer sequences you can use fillvalue (thanks @szxk): 要在更长的序列中填充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   -

You can use zip function in this case that is more efficient for small list that itertools.izip 在这种情况下,您可以使用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))

A bench-marking : 基准测试:

~$ 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

What about using pandas : 那么使用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="-")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM