![](/img/trans.png)
[英]How to print each element of a list of lists of variable length as a column in python?
[英]How to print variable length lists as columns in python?
我需要一种方法来打印多个不同长度的列表,这些列以彼此相邻的制表符分隔的列为单位,并且空单元格保持为空或包含一些填充字符(例如“-”)。
到目前为止,尝试的方法不适用于各种长度的列表,并且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 -
您可以使用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 -
在这种情况下,您可以使用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
那么使用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.