簡體   English   中英

在Python中的另一個列表中完全插入一個列表

[英]Insert one list fully inside another list in python

如何將一個列表完全插入另一個python列表中?

>>> list_one = [1,2,3]
>>> list_two = [4,5,7]

>>> list_one.insert(2, [2, 3])
>>> list_one
[1, 2, [2, 3], 3, 4, 5, 7]

但我希望結果是:

[1, 2, 2, 3, 3, 4, 5, 7]

使用切片分配(如果您想表示[1,2,4,5,6,3] ):

>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one[2:2] = list_two
>>> list_one
[1, 2, 4, 5, 6, 3]

確定要不要此結果[1,2,4,5,6,3]嗎? 如果是這樣,請嘗試以下操作:

list_one[:2]+list_two+list_one[2:]

您可以嘗試這種方式。

ActivePython 2.7.13.2713 (ActiveState Software Inc.) based on
Python 2.7.13 (default, Jan 18 2017, 15:40:43) [MSC v.1500 64 bit (AMD64)] on wi
n32
Type "help", "copyright", "credits" or "license" for more information.
>>> list_one = [1,2,3]
>>> list_two = [4,5,7]
>>> from itertools import chain
>>> result = [ elem for elem in chain(list_one[0:2], [2,3], list_one[2:], list_two)]
>>>
>>> result
[1, 2, 2, 3, 3, 4, 5, 7]
>>> result1 = list(chain(list_one[0:2], [2,3], list_one[2:], list_two))
>>> result1
[1, 2, 2, 3, 3, 4, 5, 7]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM