在python中,以2的间隔将list元素插入第二个列表

2024-05-16 05:33:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何将列表中的每个元素以2的间隔插入到第二个列表中,第一个元素插入到列表的开头

lis1 = [['g'],['h'],['i']]
lis2 = [['a'],['b'],['c'],['d'],['e'],['f']]

Expected = [['g'],['a'],['b'],['h'],['c'],['d'],['i'],['e'],['f']]

我的思维过程是将pos设置为2,并在lis1的长度大于0时进行检查,在索引0处弹出元素(第一个索引),然后插入lis2并移动到下两个位置,但我不确定如何开始,或者我的思维过程是否可行


Tags: pos元素列表间隔expectedlis1lis2
2条回答

可以使用chain.from_iterablezip

import itertools

>>> chain = itertools.chain.from_iterable
>>> s = iter(lis2)
>>> list(chain(zip(lis1,s,s)))
[['g'], ['a'], ['b'], ['h'], ['c'], ['d'], ['i'], ['e'], ['f']]

前面的解决方案是正确的,但我发现有一种有趣的方法,不用库:

import itertools


def combine1(l1, l2):
    chain = itertools.chain.from_iterable
    s = iter(lis2)
    return list(chain(zip(lis1, s, s)))


def combine2(l1, l2):
    il2 = iter(l2)
    return [x for t in [(y, next(il2, None), next(il2, None)) for y in l1] for x in t]


lis1 = [['g'],['h']]
lis2 = [['a']]

print("Accepted answer: ", combine1(lis1, lis2))
print("Alternate answer: ", combine2(lis1, lis2))

lis1 = [['g'],['h'],['i']]
lis2 = [['a'],['b']]

print("Accepted answer: ", combine1(lis1, lis2))
print("Alternate answer: ", combine2(lis1, lis2))

lis1 = [['g']]
lis2 = [['a'],['b'],['c'],['d']]

print("Accepted answer: ", combine1(lis1, lis2))
print("Alternate answer: ", combine2(lis1, lis2))

lis1 = [['g'],['h'],['i']]
lis2 = [['a'],['b'],['c'],['d'],['e'],['f']]

print("Accepted answer: ", combine1(lis1, lis2))
print("Alternate answer: ", combine2(lis1, lis2))

但这是否正确取决于在lis1lis2中可以找到什么

该脚本的输出:

Accepted answer:  []
Alternate answer:  [['g'], ['a'], None, ['h'], None, None]
Accepted answer:  [['g'], ['a'], ['b']]
Alternate answer:  [['g'], ['a'], ['b'], ['h'], None, None, ['i'], None, None]
Accepted answer:  [['g'], ['a'], ['b']]
Alternate answer:  [['g'], ['a'], ['b']]
Accepted answer:  [['g'], ['a'], ['b'], ['h'], ['c'], ['d'], ['i'], ['e'], ['f']]
Alternate answer:  [['g'], ['a'], ['b'], ['h'], ['c'], ['d'], ['i'], ['e'], ['f']]

请注意,最后一个案例使用示例数据,并且无论哪种方式都具有相同的结果

自从它出现以来,一种不同的更普遍的方法:

def generate_combine3(l1, l2, n):
    il2 = iter(l2)
    for x in l1:
        yield x
        for _ in range(n):
            yield(next(il2, None))

由于这是一个生成器,要获得与前一个函数完全相同的行为,您需要用list包装:

def combine3(l1, l2, n):
    return list(generate_combine3(l1, l2, n))

相关问题 更多 >