在特定的索引处将列表扩展为另一个列表?

9
在Python中,我们可以使用extend()方法将列表相互添加,但它会将第二个列表添加到第一个列表的末尾。
lst1 = [1, 4, 5]
lst2 = [2, 3]

lst1.extend(lst2)

Output:
[1, 4, 5, 2, 3]

我该如何将第二个列表添加到第一个元素中?使得结果是这样的;

[1, 2, 3, 4, 5 ]

我尝试使用lst1.insert(1, *lst2)却出现了错误;

TypeError: insert expected 2 arguments, got 3
3个回答

13

对于那些不喜欢阅读评论的人:

lst1 = [1, 4, 5]
lst2 = [2, 3]

lst1[1:1] = lst2
print(lst1)

输出:

[1, 2, 3, 4, 5]

-1
如果你的唯一目标是正确排序列表,那么你可以使用.extend()和.sort()。

-2

您可以通过以下两个步骤解决问题:

  • 将列表插入到另一个列表中
  • 展开结果

代码:

from collections.abc import Iterable

# https://dev59.com/THI95IYBdhLWcg3wyBCc
def flatten(xs):
    for x in xs:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            yield from flatten(x)
        else:
            yield x

xs = [1,4,5]
ys = [2,3]
xs.insert(1, ys)
print("intermediate result", xs)
xs = flatten(xs)
print(xs)

2
你不能遍历整数。这个答案会引发 TypeError - Jasmijn
@Jasmijn 非常感谢您的错误报告,我已更新flatten函数以在此情况下也能正常工作。 - Caridorc
但是如果在list函数中不调用flatten(xs),它将生成一个对象。因此,您需要将迭代器对象转换为列表,如下所示:xs = list(flatten(xs)) - Jamiu S.
@JamiuShaibu 这取决于你的情况,有时使用生成器会更有效率。 - Caridorc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接