簡體   English   中英

Python 2:在新顯式列表定義中插入現有列表

[英]Python 2: insert existing list inside of new explicit list definition

這可能是不可能的,但如果是的話,我寫的一些代碼會很方便:

ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox', ListOne, 'lazy', 'dog!']

如果我這樣做,我最終會將ListOne作為ListTwo中的一個列表。

但相反,我想將ListOne擴展為ListTwo,但我不想做類似的事情:

ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox']
ListTwo.extend(ListOne)
ListTwo.extend(['lazy', 'dog!']

這將有效,但它不像上面的代碼那樣可讀。

這可能嗎?

你可以使用+運算符來連接列表:

ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox'] + ListOne + ['lazy', 'dog!']

ListTwo將是:

['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']

另一種方法是使用切片賦值:

>>> ListOne = ['jumps', 'over', 'the']
>>> ListTwo = ['The', 'quick', 'brown', 'fox', 'lazy', 'dog!']
>>> ListTwo[4:4] = ListOne
>>> ListTwo
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
>>> ListOne = ['jumps', 'over', 'the']
>>> from itertools import chain
>>> [x for x in chain(['The', 'quick', 'brown', 'fox'], ListOne, ['lazy', 'dog!'])]
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']

為什么不連接?

>>> ListTwo = ['The', 'quick', 'brown', 'fox']
>>> ListOne = ['jumps', 'over', 'the']
>>> ListTwo + ListOne
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the']
>>> ListTwo + ListOne + ['lazy', 'dog!']
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']

暫無
暫無

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

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