【问题标题】:Copying a sublist into a main list as objects instead of lists [duplicate]将子列表作为对象而不是列表复制到主列表中[重复]
【发布时间】:2016-10-22 09:02:57
【问题描述】:
child = []
parent = [1, 3, 5, 7, 9]
index = 2
child.append(parent[:index])

当我运行这段代码时,而不是返回一个子列表

child = [1, 3]

我得到一个子列表:

child = [[1, 3]]

是否有一种单行方法可以将列表中的一些对象复制到另一个列表中而不将其放入嵌套列表中?

【问题讨论】:

  • 简单地说:使用extend 而不是append

标签: python arrays list python-3.x copy


【解决方案1】:

试试这个:

child.extend(parent[:index])

【讨论】:

    猜你喜欢
    • 2015-12-04
    • 2017-03-15
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多