繁体   English   中英

如果我只有少数子列表元素,如何从列表中删除整个子列表? 蟒蛇

[英]How do I remove whole sub-list from list, if i have only few element of the sub-list? python

我正在尝试从列表中删除子列表并获取此错误:ValueError:list.remove(x):x not in list

我希望删除子列表,尽管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

您可以检查[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)
>>> 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']]

使用包含codenamecategorylabeldate属性的ProductFood对象转移到OO方法可能会很好。

list_a = [sub for sub in list_a if not all(i in [1, 3] for i in sub)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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