【发布时间】: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