![](/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.