第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

以 python 保留順序合并兩個(gè)或多個(gè)列表的最佳方法

以 python 保留順序合并兩個(gè)或多個(gè)列表的最佳方法

滄海一幻覺(jué) 2023-04-25 17:16:42
有沒(méi)有更pythonic的方式來(lái)做到這一點(diǎn)?輸入:list1 =  [['a',1],['b',2],['c',3],['d',4]]list2 =  [['e',5],['f',6],['g',7],['h',8]]期望的輸出:out = [['a',1],['e',5],['b',2],['f',6],['c',3],['g',7],['d',4] ,['h',8]]我已經(jīng)做好了:def mergePreserveOrder(*argv):          for arg in argv:          for arg2 in argv:             if(len(arg) != len(arg2)) :                print("arrays size do not match" + str(arg) +  str(arg2))                                return     output = []        for index in range (len(argv[0])):            for arg in argv:            output.append(arg[index])        return  outputmergePreserveOrder (list1 ,list2  )
查看完整描述

3 回答

?
倚天杖

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊

您可以zip一起使用chain.from_iterable

list(chain.from_iterable(zip(list1, list2)))

示例:


from itertools import chain


list1 = [['a',1],['b',2],['c',3],['d',4]]

list2 = [['e',5],['f',6],['g',7],['h',8]]


print(list(chain.from_iterable(zip(list1, list2))))

# [['a', 1], ['e', 5], ['b', 2], ['f', 6], ['c', 3], ['g', 7], ['d', 4], ['h', 8]]


查看完整回答
反對(duì) 回復(fù) 2023-04-25
?
ABOUTYOU

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊

只需itertools.chain使用zip

>>> import itertools

>>> list(itertools.chain(*zip(list1, list2)))

[['a', 1], ['e', 5], ['b', 2], ['f', 6], ['c', 3], ['g', 7], ['d', 4], ['h', 8]]


查看完整回答
反對(duì) 回復(fù) 2023-04-25
?
qq_遁去的一_1

TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊

最通用的解決方案是模塊roundrobin中的配方:itertools

from itertools import cycle, islice


def roundrobin(*iterables):

? ? "roundrobin('ABC', 'D', 'EF') --> A D E B F C"

? ? # Recipe credited to George Sakkis

? ? num_active = len(iterables)

? ? nexts = cycle(iter(it).__next__ for it in iterables)

? ? while num_active:

? ? ? ? try:

? ? ? ? ? ? for next in nexts:

? ? ? ? ? ? ? ? yield next()

? ? ? ? except StopIteration:

? ? ? ? ? ? # Remove the iterator we just exhausted from the cycle.

? ? ? ? ? ? num_active -= 1

? ? ? ? ? ? nexts = cycle(islice(nexts, num_active))


list1 =? [['a',1],['b',2],['c',3],['d',4]]

list2 =? [['e',5],['f',6],['g',7],['h',8]]


print(list(roundrobin(list1, list2)))

產(chǎn)生你想要的輸出。


chain與+不同zip,此解決方案適用于不均勻長(zhǎng)度的輸入,其中zip將靜默丟棄超出最短輸入長(zhǎng)度的所有元素。


查看完整回答
反對(duì) 回復(fù) 2023-04-25
  • 3 回答
  • 0 關(guān)注
  • 151 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)