如果我有两个列表(可能具有不同的长度):
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
result = [11,22,33,44]
我正在做:
for element in f:
if element in x:
f.remove(element)
我得到了
result = [11,22,33,44,4]
感谢@Ahito:
In : list(set(x).symmetric_difference(set(f)))
Out: [33, 2, 22, 11, 44]
这篇文章有一个简洁的图表,解释了对称差异的作用。
在集合上使用这段 Python 文档:
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
我想出了这段代码来从两个列表中获取唯一元素:
(set(x) | set(f)) - (set(x) & set(f))
或者稍微修改一下返回
list
:
list((set(x) | set(f)) - (set(x) & set(f))) #if you need a list
这里:
|
运算符返回 x
、f
或 both&
运算符返回 both x
和 f
-
运算符从 &
中减去 |
的结果,并为我们提供仅在其中一个列表中唯一呈现的元素如果您想要两个列表中的唯一元素,这应该可行:
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
res = list(set(x+f))
print(res)
# res = [1, 2, 3, 4, 33, 11, 44, 22]
基于新(已关闭)问题中对此问题的澄清:
如果您想要第二个列表中未出现在第一个列表中的所有项目,您可以编写:
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
result = set(f) - set(x) # correct elements, but not yet in sorted order
print(sorted(result)) # sort and print
# Output: [11, 22, 33, 44]
如果您只想从两个列表中获取唯一元素,那么您可以通过..
获取它a=[1,2,3,4,5]
b= [2,4,1]
list(set(a) - set(b))
OP:- [3, 5]
x = [1, 2, 3, 4]
f = [1, 11, 22, 33, 44, 3, 4]
list(set(x) ^ set(f))
[33, 2, 22, 11, 44]
输入:
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
代码:
l = list(set(x).symmetric_difference(set(f)))
print(l)
输出:
[2, 22, 33, 11, 44]
您的方法不会获得唯一元素“2”。 怎么样:
list(set(x).intersection(f))
简化版本并支持@iopheam的答案。
Set
减法。# original list values
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
# updated to set's
y = set(x) # {1, 2, 3, 4}
z = set(f) # {1, 33, 3, 4, 11, 44, 22}
# parsed to the result variable
result = z - y # {33, 11, 44, 22}
# printed using the sorted() function to display as requested/stated by the op.
print(f"Result of f - x: {sorted(result)}")
# Result of f - x: [11, 22, 33, 44]
v_child_value = [{'a':1}, {'b':2}, {'v':22}, {'bb':23}]
shop_by_cat_sub_cats = [{'a':1}, {'b':2}, {'bbb':222}, {'bb':23}]
unique_sub_cats = []
for ind in shop_by_cat_sub_cats:
if ind not in v_child_value:
unique_sub_cats.append(ind)
unique_sub_cats = [{'bbb': 222}]
从两个列表创建唯一列表的Python代码:
a=[1,1,2,3,5,1,8,13,6,21,34,55,89,1,2,3]
b=[1,2,3,4,5,6,7,8,9,10,11,12,2,3,4]
m=list(dict.fromkeys([a[i] for i in range(0,len(a)) if a [i] in a and a[i] in b and a[i]]))
print(m)
L=[]
For i in x:
If i not in f:
L. Append(I)
For i in f:
If I not in x:
L. Append(I)
Return L
您也可以在两个Python列表中找到唯一元素,而无需内置函数。 这是从两个列表中查找唯一元素的最短方法,无需内置函数
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
print([i for i in x + f if (i not in x or i not in f)])