Python,计算列表差异 [英] Python, compute list difference

查看:100
本文介绍了Python,计算列表差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,计算两个列表之间的差异的最佳方法是什么?

In Python, what is the best way to compute the difference between two lists?

示例

A = [1,2,3,4]
B = [2,5]

A - B = [1,3,4]
B - A = [5]

推荐答案

如果您不关心项目的顺序或重复,请使用set.如果您这样做,请使用列表理解:

Use set if you don't care about items order or repetition. Use list comprehensions if you do:

>>> def diff(first, second):
        second = set(second)
        return [item for item in first if item not in second]

>>> diff(A, B)
[1, 3, 4]
>>> diff(B, A)
[5]
>>> 

这篇关于Python,计算列表差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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