2012-12-15 22 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)