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

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用Pythonic方式以交替方式組合兩個列表的方法?

用Pythonic方式以交替方式組合兩個列表的方法?

慕運維8079593 2019-10-17 16:04:34
我有兩個列表,保證其中一個比第二個多包含一個項目。我想知道最Python化的方式來創(chuàng)建一個新列表,該列表的偶數(shù)索引值來自第一個列表,其奇數(shù)索引值來自第二個列表。# example inputslist1 = ['f', 'o', 'o']list2 = ['hello', 'world']# desired output['f', 'hello', 'o', 'world', 'o']這可行,但不是很漂亮:list3 = []while True:    try:        list3.append(list1.pop(0))        list3.append(list2.pop(0))    except IndexError:        break還有什么可以實現(xiàn)的呢?什么是最Python化的方法?
查看完整描述

3 回答

?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

這是切片的一種方法:


>>> list1 = ['f', 'o', 'o']

>>> list2 = ['hello', 'world']

>>> result = [None]*(len(list1)+len(list2))

>>> result[::2] = list1

>>> result[1::2] = list2

>>> result

['f', 'hello', 'o', 'world', 'o']


查看完整回答
反對 回復 2019-10-17
?
狐的傳說

TA貢獻1804條經驗 獲得超3個贊

在itertools文檔中有一個配方:


from itertools import cycle, islice


def roundrobin(*iterables):

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

    # Recipe credited to George Sakkis

    pending = len(iterables)

    nexts = cycle(iter(it).next for it in iterables)

    while pending:

        try:

            for next in nexts:

                yield next()

        except StopIteration:

            pending -= 1

            nexts = cycle(islice(nexts, pending))


查看完整回答
反對 回復 2019-10-17
?
呼喚遠方

TA貢獻1856條經驗 獲得超11個贊

如果沒有itertools,并假設l1比l2長1個項目:


>>> sum(zip(l1, l2+[0]), ())[:-1]

('f', 'hello', 'o', 'world', 'o')

使用itertools并假設列表不包含None:


>>> filter(None, sum(itertools.izip_longest(l1, l2), ()))

('f', 'hello', 'o', 'world', 'o')


查看完整回答
反對 回復 2019-10-17
  • 3 回答
  • 0 關注
  • 530 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號