2017-08-28 81 views
1

我試圖將2個具有不同數據和大小的列表合併爲1,並將較小的列表「換行」。我正在尋找一種乾淨的方式來做到這一點,例如將兩個不同大小的列表組合成一個組合

輸入:

list1 = ['apple', 'orange', 'strawberry', 'avocado'] 
list2 = ['1','2','3'] 

輸出:

[ 
    {"l1": "apple", "l2": "1"}, 
    {"l1": "orange", "l2": "2"}, 
    {"l1": "strawberry", "l2": "3"}, 
    {"l1": "avocado", "l2": "1"} 
] 

注意,對於"avocado",我們又回到"1"和周圍包裹列表2。

顯而易見的(看起來醜陋的)解決方案是從一個空的列表開始,在一個循環中有兩個索引,每個迭代附加一個新的列表項,並且當它到達時,較小的一個'包裝'到開始結束。 Python 2.7中有這樣乾淨的方法嗎?

+2

考慮'itertools.izip'沿着'itertools.cycle'你的短名單。 – erewok

回答

6

您可以使用itertools.cycle包住第二列表:

from itertools import cycle 

lst = [dict(zip(['l1', 'l2'], tup)) for tup in zip(list1, cycle(list2))] 
2

你可以使用一個生成器,避免追加到一個空表:

def func(l1, l2): 
    length1 = len(l1) 
    length2 = len(l2) 
    for idx in range(max(length1, length2)): 
     # I use the modulo so the indices wrap around. 
     yield {'l1': l1[idx % length1], 'l2': l2[idx % length2]} 

list(func(list1, list2)) 
# [{'l1': 'apple', 'l2': '1'}, 
# {'l1': 'orange', 'l2': '2'}, 
# {'l1': 'strawberry', 'l2': '3'}, 
# {'l1': 'avocado', 'l2': '1'}] 

然而itertools.cycle(見對方的回答)是可能好多了。

2

爲簡單起見,您只能使用enumerate;然而,一個清潔的解決方案將涉及itertools.cycle

list1 = ['apple', 'orange', 'strawberry', 'avocado'] 
list2 = ['1','2','3'] 
new_list = [{"li":a, "l2":list2[i%len(list2)]} for i, a in enumerate(list1)] 

輸出:

[{'l2': '1', 'li': 'apple'}, {'l2': '2', 'li': 'orange'}, {'l2': '3', 'li': 'strawberry'}, {'l2': '1', 'li': 'avocado'}] 
+0

道歉。我只注意到我們的答案是一樣的,而且你的答案也早一些。將時間添加到你的,我會刪除我的。 – Alexander

+0

@Alexander完全沒問題!謝謝。 – Ajax1234

0
def processing(opt, longlist, shortlist): 
    def processing_iter(inL, refL, outL): 
    if refL == []: 
     return outL 
    elif inL == []: 
     return processing_iter(shortlist, refL[1:], outL+opt(refL[0], shortlist[0])) 
    else: 
     return processing_iter(inL[1:], refL[1:], outL+opt(refL[0], inL[0])) 
    return processing_iter(shortlist, longlist, []) 


def makedict(a,b): return [{"l1":a, "l2":b}] 

list1 = ['apple', 'orange', 'strawberry', 'avocado'] 
list2 = ['1','2','3'] 
print(processing(makedict,list1, list2))