是否可以将一个列表的特定部分插入另一个列表中的特定位置?

时间:2016-01-26 17:58:06

标签: python list python-3.x

我对Python很新,除了发现它很有用而且很容易理解之外,还有一些我不清楚的事情,这个问题。

是否可以将一个列表的特定部分插入另一个列表中的特定位置?

比如说,我有一个叫做' a'的列表,在这个列表中我有以这种格式的数字1,3和5:

a = [1, 3, 5]

我还有一个名为' b'其中包含此格式的数字2和4:

b = [2, 4]

我的最终目标是列出' a'改为:

a = [1, 2, 3, 4, 5]

正如您所看到的,这将要求我指定使用两个列表的索引将它们组合成这种自定义格式的一个列表,我不确定如何解决这个问题。

我无意中遗漏了一个重要的细节,这就是我想要使用'插入'功能而不是'追加'。

3 个答案:

答案 0 :(得分:0)

是。只需使用insert()并将第二个参数作为列表元素。

a = [1, 3, 5]
b = [2, 4]
# The first argument is the index to insert it at.
# The second is the actual item to be inserted.
a.insert(1, b[0]) # [1, 2, 3, 5]
a.insert(3, b[1]) # [1, 2, 3, 4, 5]

请注意,如果您只想对a进行排序,则可以使用:

for item in b:
    a.append(item) # Order does not matter, we will sort it later
# a is currently [1, 3, 5, 2, 4] since append() adds to the end of the list
a.sort()
# a is now [1, 2, 3, 4, 5] as sort() re-ordered it

或者如果你想要它更简单,连接它们然后排序:

a = a + b # [1, 3, 5, 2, 4]
a.sort() # [1, 2, 3, 4, 5]

让我知道这是不清楚或不是你想要的。

答案 1 :(得分:0)

这对你有什么用?

a = [1,2,5,6,7]
b = [3,4]
for n,k in enumerate(a):
     if(k<b[0]):
         a = a[0:n]+b+a[n:]
         break
print(a)

使用冒号切片数组是非常有用的。

答案 2 :(得分:0)

如果您正在交错列表,可以使用izip_longest

对其进行压缩
>>> a = [1, 3, 5]
>>> b = [2, 4]

>>> from itertools import izip_longest

>>> [c for pair in izip_longest(a, b)
...  for c in pair if c is not None]
[1, 2, 3, 4, 5]