我正在尝试从列表中删除子列表并收到此错误: ValueError:list.remove(x):x不在列表中
我希望删除子列表,尽管x只有少数来自子字符串
类似的东西:
list_a=[[1,2,3],[4,5,6]]
list_a.remove([1,3])
list_a
[4,5,6]
来自以下评论:
我有产品清单:
products=[['0001', 'Hummus', 'Food', 'ISR', '10-04-2015'], ['0002', 'Guinness', 'Food', 'IRL', '11-04-2015']]
lst[0]
,lst[2]
和lst[3]
对于每种产品都是唯一的。我希望通过这三个元素来删除整个子列表:
>>> 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
答案 0 :(得分:5)
您可以检查[1,3]
是否为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测试s中的每个元素是否都在t
使用list_a[:]
更改原始列表。
使用您的产品列表完全相同:
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']]
使用循环,如果它更容易遵循,你可以组合反转和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)
答案 1 :(得分:2)
>>> 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]]
现在实际问题已经揭晓:
>>> 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']]
使用包含Product
,Food
,code
,{{1的name
或category
对象,转移到OO方法可能会更好}}和label
属性。
答案 2 :(得分:2)
list_a = [sub for sub in list_a if not all(i in [1, 3] for i in sub)]