计算列表差异 [英] Compute list difference

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

问题描述

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

示例

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

解决方案

如果顺序无关,你可以简单地计算一下集合差:

<预><代码>>>>设置([1,2,3,4]) - 设置([2,5])设置([1, 4, 3])>>>设置([2,5]) - 设置([1,2,3,4])设置([5])

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

example

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

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

解决方案

If the order does not matter, you can simply calculate the set difference:

>>> set([1,2,3,4]) - set([2,5])
set([1, 4, 3])
>>> set([2,5]) - set([1,2,3,4])
set([5])

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

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