2015-10-09 8 views
5

(誰かがより良いタイトルを提案できる場合は、ぜひとも編集してください)可変長の文字数で固定長のPythonリストを拡張するには?

が、その正確な長さは不明であるが、それが知られているため、常に5以下になりますlistリスト1を考えると、私は固定長5の別々の空listLIST2を埋めるために探しています、 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 

(多くの空の文字列を追加する方法を決定する)これを達成するneatest方法は何ですか?

答えて

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, '?'] 
関連する問題