Is there a way to get the difference and intersection of tuples or lists in Python?(有没有办法在 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.
推荐答案
如果顺序无所谓,可以使用set 为此.它实现了交集和差异.
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 中获取元组或列表的差异和交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有办法在 Python 中获取元组或列表的差异和交集?
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
