I'm trying to remove sub-list from list and gets this error: ValueError: list.remove(x): x not in list
I wish to remove the sub-list despite the fact that x have only few elemnt from sub-string
something like that:
list_a=[[1,2,3],[4,5,6]]
list_a.remove([1,3])
list_a
[4,5,6]
From comments below:
i got list of products:
products=[['0001', 'Hummus', 'Food', 'ISR', '10-04-2015'], ['0002', 'Guinness', 'Food', 'IRL', '11-04-2015']]
lst[0]
, lst[2]
and lst[3]
are unique for each product. i wish to remove the whole sub list, by having this three elemnts like:
>>> products.remove(['0001', 'Food', 'ISR'])
>>> products
['0002', 'Guinness', 'Food', 'IRL', '11-04-2015']
.
def del_product(depot, product_data):
'''
del_product
delets a validated product data from the depot
if such a product does not exist in the depot
then no action is taken
arguments:
depot - list of lists
product_data - list
return value: boolean
'''
# Your code goes her
if validate_product_data(product_data)==True:
for product in depot:
if equal_products(product, product_data)==True:
rem = set(product_data)
for x in reversed(depot):
if rem.issubset(x):
depot.remove(x)
return True
else:
continue
return False
You can check if [1,3]
is a subset with set.issubset :
list_a = [[1,2,3],[4,5,6]]
rem = set([1,3])
list_a[:] = [ x for x in list_a if not rem.issubset(x)]
print(list_a)
s.issubset(t) s <= t test whether every element in s is in t
Using list_a[:]
changes the original list.
With your products list it is exactly the same:
products=[['0001', 'Hummus', 'Food', 'ISR', '10-04-2015'], ['0002', 'Guinness', 'Food', 'IRL', '11-04-2015']]
rem = set(['0001', 'Food', 'ISR'])
products[:] = [ x for x in products if not rem.issubset(x)]
print(products)
[['0002', 'Guinness', 'Food', 'IRL', '11-04-2015']]
Using a loop if it makes it easier to follow, you can combine reversed and issubset:
products=[['0001', 'Hummus', 'Food', 'ISR', '10-04-2015'], ['0002', 'Guinness', 'Food', 'IRL', '11-04-2015']]
rem = set(['0001', 'Food', 'ISR'])
for x in reversed(products):
if rem.issubset(x):
products.remove(x)
print(products)
>>> list_a = [[1,2,3],[4,5,6]]
>>> bad = [1,3]
>>> list_a = [l for l in list_a if all(e not in l for e in bad)]
>>> list_a
[[4, 5, 6]]
Now that the actual question has been revealed:
>>> products=[['0001', 'Hummus', 'Food', 'ISR', '10-04-2015'], ['0002', 'Guinness', 'Food', 'IRL', '11-04-2015']]
>>> to_remove=['0001', 'Food', 'ISR']
>>> products = [l for l in products if [l[0], l[2], l[3]] != to_remove]
>>> products
[['0002', 'Guinness', 'Food', 'IRL', '11-04-2015']]
It might be good to move to an OO approach, with a Product
or Food
object containing code
, name
, category
, label
, and date
attributes.
list_a = [sub for sub in list_a if not all(i in [1, 3] for i in sub)]
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.