为了账号安全,请及时绑定邮箱和手机立即绑定

用Pythonic方式以交替方式组合两个列表的方法?

用Pythonic方式以交替方式组合两个列表的方法?

慕运维8079593 2019-10-17 16:04:34
我有两个列表,保证其中一个比第二个多包含一个项目。我想知道最Python化的方式来创建一个新列表,该列表的偶数索引值来自第一个列表,其奇数索引值来自第二个列表。# 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还有什么可以实现的呢?什么是最Python化的方法?
查看完整描述

3 回答

?
杨魅力

TA贡献1811条经验 获得超5个赞

这是切片的一种方法:


>>> 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 关注
  • 453 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信