2015-10-09 54 views
5

(如果有人可以建議更好的標題,盡一切辦法繼續編輯)。如何通過可變數量的字符擴展一個固定長度的Python列表?

給出一個list列表1其確切長度未知,但已知的是,這將永遠是小於或等於5,我找填充一個單獨的空list列表2,固定長度5,在list1的的值,其空字符串填充瞭如果list2中的尺寸小於5。

例如如果list1的= [1,2,3]

然後list2中應該是[1,2,3, '', '']

等。

所以:

if len(list1) < 5: 
    list2.extend(list1) 
    # at this point, I want to add the empty strings, completing the list of size 5 

什麼是實現這一目標的(確定有多少空字符串添加)最巧妙的方法?

回答

5
list2 = list1 + [''] * (5 - len(list1)) 
+1

高雅最高分。 – Pyderman

0

另一種方式:

extend_list = lambda list, len=5, fill_with='': map(lambda e1, e2: e1 if e2 is None else e2, [fill_with]*len, list) 
print extend_list([1, 2, 3]) 
>>> [1, 2, 3, '', ''] 
print extend_list([1, 2], 3, '?') 
>>> [1, 2, '?'] 
相關問題