在列表中查找非常见元素 [英] Find non-common elements in lists

查看:85
本文介绍了在列表中查找非常见元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一段可以自动分解表达式的代码.例如, 如果我有两个列表[1,2,3,4]和[2,3,5],则代码应该能够在两个列表[2,3]中找到相同的元素,并将其余部分组合元素一起在一个新列表中,即[1,4,5].

I'm trying to write a piece of code that can automatically factor an expression. For example, if I have two lists [1,2,3,4] and [2,3,5], the code should be able to find the common elements in the two lists, [2,3], and combine the rest of the elements together in a new list, being [1,4,5].

从此帖子中:如何查找列表交集? 我看到可以通过

From this post: How to find list intersection? I see that the common elements can be found by

set([1,2,3,4]&set([2,3,5]). 

是否有一种简单的方法可以从每个列表中检索非公共元素,在我的示例中为[1,4]和[5]?

Is there an easy way to retrieve non-common elements from each list, in my example being [1,4] and [5]?

我可以继续进行一个for循环:

I can go ahead and do a for loop:

lists = [[1,2,3,4],[2,3,5]]
conCommon = []
common = [2,3]
for elem in lists:
    for elem in eachList:
    if elem not in common:
        nonCommon += elem

但是,这似乎是多余且效率低下的. Python是否提供任何方便的功能可以做到这一点?在此先感谢!

But this seems redundant and inefficient. Does Python provide any handy function that can do that? Thanks in advance!!

推荐答案

set使用对称差分运算符(又名XOR运算符):

Use the symmetric difference operator for sets (aka the XOR operator):

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

这篇关于在列表中查找非常见元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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