2017-05-09 99 views
1

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

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(最大),我如何将其余的附加到一个新的列表?

+1

'return [x for the list if x!= value]'?还是有更深的理由来改变'列表'? – timgeb

+0

尝试使用for循环 – Matt

+0

如果您必须对原始列表进行变异,您可以在枚举(列表)中为idx,item:if item == value:newlist.append(thelist.pop(idx))',' pop()'调用每次都是O(n) –

回答

0
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] 
相关问题