从与lis中的元素匹配的集合中删除元素

2024-04-26 14:59:23 发布

您现在位置:Python中文网/ 问答频道 /正文

从集合中删除条目时遇到问题

# Remove all out-of-stock items from our list
# This is O(n^3), unfortunately.
for x in oos:
    for asin in asins:
        if x == asin[0]:
            del asin

“asins”是一组元组,创建方式如下:

asins.add(tuple((asin, c, s)))

oos是一个列表。我试图删除“asins”中的所有条目,这些条目也存在于“oos”中。不幸的是,“del asin”实际上不起作用,因为它没有从“asin”中删除条目


Tags: ofinfromforstockour条目items
2条回答

del asin这样使用只会删除局部变量asin,而不是实际引用的对象,尤其是集合中包含的对象

相反,您需要调用^{}来删除元素:

asins.remove(asin)

但是,您实际上不需要在集合中循环以从中删除项目。集合的全部好处是,您具有固定时间访问权限,因此您可以在固定时间内检查成员资格,从而使循环很少有用

但是,由于您存储的是复杂的元组,并且您只通过第一个元组元素来标识元素,因此在这里无法这样做。您应该做的是切换到更合适的集合。在您的情况下,您需要一本字典:

# convert your set of tuples to a dictionary
# ideally, you would store the data like this in the first place
asins = { asin[0]: asin for asin in asins }

然后您可以执行以下操作:

for x in oos:
    del asins[x] # here, you can use del

在一般情况下,这将是O(n)

您可以使用生成器表达式轻松地执行此操作。它不应该那么低效,但我也不会说它有效率

asins = {t for t in asins if t[0] not in set(oos)}

请注意,这将创建一个新的集合。这可能是最好的,因为您无法迭代一个集合并在适当的位置对其进行更改。例如,将del asin更改为asins.remove(asin)将引发RuntimeError

相关问题 更多 >