找到列出了常见的元素 [英] find common elements in lists
问题描述
我想写一张code,可以自动因素的前pression。例如, 如果我有两个列表[1,2,3,4]及[1,2,3,5],则code应能找到在两个列表的公共元素,[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].
从这个帖子:的Python:如何找到列表路口 我看到常见的元素可以通过
From this post: Python: 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]?
我可以继续做一个循环:
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!!
推荐答案
使用对称差运算符设置
S(又名XOR运算符):
Use the symmetric difference operator for set
s (aka the XOR operator):
>>> set([1,2,3]) ^ set([3,4,5])
set([1, 2, 4, 5])
这篇关于找到列出了常见的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!