我正在尝试编写一段可以自动分解表达式的代码.例如,如果我有两个列表 [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 set
s (aka the XOR operator):
>>> set([1,2,3]) ^ set([3,4,5])
set([1, 2, 4, 5])
这篇关于查找列表中不常见的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!