首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取两个列表之间的差异

获取两个列表之间的差异
EN

Stack Overflow用户
提问于 2010-08-12 03:38:10
回答 31查看 1.1M关注 0票数 1K

我在Python中有两个列表,如下所示:

代码语言:javascript
运行
复制
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']

我需要用第一个列表中没有出现在第二个列表中的条目创建第三个列表。从这个例子中,我必须得到

代码语言:javascript
运行
复制
temp3 = ['Three', 'Four']

有没有不需要循环和检查的快速方法?

EN

Stack Overflow用户

发布于 2015-12-18 06:20:50

如果你想要更像变更集的东西...可以使用计数器

代码语言:javascript
运行
复制
from collections import Counter

def diff(a, b):
  """ more verbose than needs to be, for clarity """
  ca, cb = Counter(a), Counter(b)
  to_add = cb - ca
  to_remove = ca - cb
  changes = Counter(to_add)
  changes.subtract(to_remove)
  return changes

lista = ['one', 'three', 'four', 'four', 'one']
listb = ['one', 'two', 'three']

In [127]: diff(lista, listb)
Out[127]: Counter({'two': 1, 'one': -1, 'four': -2})
# in order to go from lista to list b, you need to add a "two", remove a "one", and remove two "four"s

In [128]: diff(listb, lista)
Out[128]: Counter({'four': 2, 'one': 1, 'two': -1})
# in order to go from listb to lista, you must add two "four"s, add a "one", and remove a "two"
票数 3
EN
查看全部 31 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3462143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档