2017-05-09 92 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] 
相關問題