【问题标题】:Append items that weren't removed into separate list [duplicate]将未删除的项目附加到单独的列表中[重复]
【发布时间】:2017-05-09 20:54:36
【问题描述】:

我想知道如何将所有未删除的项目附加到新列表中。

challenge = [1, 0, 9, 8, 5, 4, 1, 9, 3, 2, 3, 5, 6, 9]

def remove_values(thelist, value):
    newlist = []
    while value in thelist:
        thelist.remove(value)
        newlist.append()

bye = remove_values(challenge, max(challenge))

例如,如果我删除所有 9(最大值),我如何将其余部分添加到新列表中?

【问题讨论】:

  • return [x for x in thelist if x != value] ?还是有更深层次的理由改变thelist
  • 试试 for 循环
  • 如果你必须改变原始列表,你可以做for idx,item in enumerate(thelist): if item == value: newlist.append(thelist.pop(idx)),虽然每次pop()调用都是O(n)

标签: python python-3.x


【解决方案1】:
challenge = [1, 0, 9, 8, 5, 4, 1, 9, 3, 2, 3, 5, 6, 9]

# This will append every item to a new List where the value not is max
# You won't need 2 lists to achieve what you want, it can be done with a simple list comprehension
removed_list = [x for x in challenge if x != max(challenge)]
print(removed_list)
# will print [1, 0, 8, 5, 4, 1, 3, 2, 3, 5, 6]

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2020-08-04
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    相关资源
    最近更新 更多