3

这可能是不可能的,但如果是的话,我正在编写的一些代码会很方便:

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!']

这会起作用,但它不像上面的代码那样可读。

这可能吗?

4

4 回答 4

8

您可以只使用+运算符来连接列表:

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

ListTwo将会:

['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
于 2013-07-16T07:26:15.647 回答
2

另一种选择是使用切片分配:

>>> 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!']
于 2013-07-16T07:27:15.617 回答
1
>>> 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!']
于 2013-07-16T07:31:28.533 回答
0

为什么不串联?

>>> 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!']
于 2013-07-16T07:38:13.603 回答