2012-12-15 21 views
4

我已经列出了与要素的数量不均衡的列表:的Python:移调不平行转换成列

[['a','b','c'], ['d','e'], [], ['f','g','h','i']] 

我在ReportLab的显示表,我想显示的栏目。据我所知,RL只用表格(Platypus)的数据作为上面的行格式。

我可以使用循环来切换,但我觉得有一个列表理解会更快,更Pythonic。我还需要在元素列用完的列中留出空格。

需要的产物,应该是:

[['a','d','','f'],['b','e','','g'],['c','','','h'],['','','','i']] 

编辑:例子应该是字符串,而不是数字

感谢您的帮助!

+1

你尝试的http:// docs.python.org/2/library/itertools.html#itertools.izip_longest – akaRem

回答

10

itertools.izip_longest()需要一个fillvalue的说法。在Python 3上,它是itertools.zip_longest()

>>> l = [[1,2,3], [4,5], [], [6,7,8,9]] 
>>> import itertools 
>>> list(itertools.izip_longest(*l, fillvalue="")) 
[(1, 4, '', 6), (2, 5, '', 7), (3, '', '', 8), ('', '', '', 9)] 

如果确实需要子列表而不是元组:

>>> [list(tup) for tup in itertools.izip_longest(*l, fillvalue="")] 
[[1, 4, '', 6], [2, 5, '', 7], [3, '', '', 8], ['', '', '', 9]] 

当然,这也适用于字符串:

>>> l = [['a','b','c'], ['d','e'], [], ['f','g','h','i']] 
>>> import itertools 
>>> list(itertools.izip_longest(*l, fillvalue="")) 
[('a', 'd', '', 'f'), ('b', 'e', '', 'g'), ('c', '', '', 'h'), ('', '', '', 'i')] 

它甚至是这样的:

>>> l = ["abc", "de", "", "fghi"] 
>>> list(itertools.izip_longest(*l, fillvalue="")) 
[('a', 'd', '', 'f'), ('b', 'e', '', 'g'), ('c', '', '', 'h'), ('', '', '', 'i')] 
+0

(+1)尼斯...... – NPE

+0

这是否适用于字符串?为了让我的例子变得简单,我认为我误导了我的目的。 – DeltaG

+0

是的,为什么不呢?你知道,很容易找出...... –

1

这是另一种方式:

>>> map(lambda *z: map(lambda x: x and x or '', z), *l) 
[['a', 'd', '', 'f'], ['b', 'e', '', 'g'], ['c', '', '', 'h'], ['', '', '', 'i']] 
0

另一种方式,我认为是简单的,如果你能忍受无值,而不是空字符串:

a = [['a','b','c'], ['d','e'], [], ['f','g','h','i']] 
map(lambda *z: list(z), *a) 
#[['a', 'd', None, 'f'], ['b', 'e', None, 'g'], ['c', None, None, 'h'], [None, None, None, 'i']] 
0
map(lambda *z: [s if s else '' for s in z], *a) 

map(lambda *z: [('', s)[s>None] for s in z], *a)