【问题标题】:Python 2: insert existing list inside of new explicit list definitionPython 2:在新的显式列表定义中插入现有列表
【发布时间】:2013-07-16 07:24:52
【问题描述】:

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

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

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

这可能吗?

【问题讨论】:

标签: python list


【解决方案1】:

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

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

ListTwo 将是:

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

【讨论】:

  • 原来是让它工作的最简单方法。谢谢,我总是忘记列表连接。
【解决方案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!']

【讨论】:

  • 这避免了@grc 的答案创建的临时列表
【解决方案3】:
>>> 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!']

【讨论】:

    【解决方案4】:

    为什么不连接?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 2019-07-06
      相关资源
      最近更新 更多