有没有一种方法可以获取Python中元组或列表的差异和交集? [英] Is there a way to get the difference and intersection of tuples or lists in Python?

查看:356
本文介绍了有没有一种方法可以获取Python中元组或列表的差异和交集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有列表:

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

c = a * b

应该给我:

c = [4, 5]

c = a - b

应该给我:

c = [1, 2, 3]

这是可用于Python还是我必须自己编写它?

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.

推荐答案

如果顺序无关紧要,则可以使用

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])

以下是这些操作的时间复杂度信息: https://wiki.python.org /moin/TimeComplexity#set .注意,换位的顺序会改变操作的复杂性.

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.

如果元素可以出现多次(以前称为 multiset ),则可以使用 Counter :

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})

这篇关于有没有一种方法可以获取Python中元组或列表的差异和交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆