Retaining order while using Python's set difference

后端 未结 3 1396
余生分开走
余生分开走 2020-12-16 13:36

I\'m doing a set difference operation in Python:

x = [1, 5, 3, 4]
y = [3]

result = list(set(x) - set(y))
print(result)

I\'m getting:

3条回答
  •  时光取名叫无心
    2020-12-16 13:53

    Sets are unordered, so you will need to put the results back in the correct order after doing your set difference. Fortunately you already have the elements in the order you want, so this is easy.

    diff = set(x) - set(y)
    result = [o for o in x if o in diff]
    

    But this can be streamlined; you can do the difference as part of the list comprehension (though it is arguably slightly less clear that that's what you're doing).

    sety = set(y)
    result = [o for o in x if o not in sety]
    

    You could even do it without creating the set from y, but the set will provide fast membership tests, which will save you significant time if either list is large.

提交回复
热议问题