Is there a way to get the difference and intersection of tuples or lists in Python? [duplicate]

喜欢而已 提交于 2019-11-30 05:59:58

问题


If I have lists:

a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]

c = a * b

should give me:

c = [4, 5]

and

c = a - b

should give me:

c = [1, 2, 3]

Is this available for Python or do I have to write it myself?

Would the same work for tuples? I will likely use lists as I will be adding them, but just wondering.


回答1:


If the order doesn't matter, you can use set for this. It has intersection and difference implemented.

>>> a = set([1, 2, 3, 4, 5])
>>> b = set([4, 5, 6, 7, 8])
>>> a.intersection(b)
set([4, 5])
>>> a.difference(b)
set([1, 2, 3])

Here is the info of time complexities of these operations: https://wiki.python.org/moin/TimeComplexity#set. Notice, that the order of subtrahends changes operation complexity.

If element can occur several times (formally it is called multiset), you can use Counter:

>>> from collections import Counter
>>> a = Counter([1, 2, 3, 4, 4, 5, 5])
>>> b = Counter([4, 4, 5, 6, 7, 8])
>>> a - b
Counter({1: 1, 2: 1, 3: 1, 5: 1})
>>> a & b
Counter({4: 2, 5: 1})


来源:https://stackoverflow.com/questions/20179519/is-there-a-way-to-get-the-difference-and-intersection-of-tuples-or-lists-in-pyth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!