简体   繁体   中英

A python function for removing sublist from nested list

I want to remove all occurrences of a list from list of lists. By that I mean I want to filter out all the occurrences of a given list. Eg

list = [[1,2,3], [3,2,1] ,[4,2,5],[1,2,3]]
list.removeList([1,2,3])
list=[[3,2,1],[4,2,5]]

I was thinking of using a filter or.remove() but it is giving me error. And for the filter I don't know what approach I should start with

Use a list comprehension

l = [sublist for sublist in l if sublist != [1, 2, 3]]
list1 = [[1,2,3], [3,2,1] ,[4,2,5],[1,2,3]]
list2= list1

for i in list1:
    if i==[1,2,3]:
        list2.remove(i)

With append

list1 = [[1,2,3], [3,2,1] ,[4,2,5],[1,2,3]]
list2= []

for i in list1:
    if i!=[1,2,3]:
        list2.append(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM