簡體   English   中英

將兩個大小不同的列表合並為一組

[英]Combine two differently sized lists into a combined set

我正在嘗試將具有不同數據和大小的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"並包裹在list2周圍。

一個顯而易見的(丑陋的)解決方案是從一個空列表開始,在一個循環中有2個索引,每次迭代都附加一個新的列表項,而較小的一個在到達末尾時“換行”。 在python 2.7中有沒有一種干凈的方法可以做到這一點?

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

from itertools import cycle

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

您可以使用避免附加到空列表的生成器:

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 (請參閱其他答案)可能要好得多。

您僅可以為了簡單起見使用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'}]
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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM