两个列表之间的唯一值
unique values between 2 lists
我正在尝试查找唯一值 b/w 2 个列表,但此逻辑似乎不起作用
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
for element in f:
if element in x:
f.remove(element)
print f
期望的输出
[11, 22, 33, 44]
实际产量
[11, 22, 33, 44, 4]
Get only unique elements from two lists python
同样在这里问
解决方案:
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
res = list(set(x+f))
print(res)
[1, 2, 3, 4, 33, 11, 44, 22]
如你所见,它添加 1,2,3,4 不是我需要的输出
在关闭和重新打开所有麻烦之后,我觉得应该有人真正回答这个问题。
有不同的方法可以达到预期的效果:
列表理解:[i for i in f if i not in x]
。也许效率较低但保持秩序。感谢 Chris_Rands(上面的评论)。
设置操作:set(f) - set(x)
。对于较大的列表可能更有效但不保留顺序。 Gredit 转到 mpf82. This also removes duplicates in f
, as pointed out by asongtoruin.
我正在尝试查找唯一值 b/w 2 个列表,但此逻辑似乎不起作用
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
for element in f:
if element in x:
f.remove(element)
print f
期望的输出
[11, 22, 33, 44]
实际产量
[11, 22, 33, 44, 4]
Get only unique elements from two lists python
同样在这里问 解决方案:
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
res = list(set(x+f))
print(res)
[1, 2, 3, 4, 33, 11, 44, 22]
如你所见,它添加 1,2,3,4 不是我需要的输出
在关闭和重新打开所有麻烦之后,我觉得应该有人真正回答这个问题。
有不同的方法可以达到预期的效果:
列表理解:
[i for i in f if i not in x]
。也许效率较低但保持秩序。感谢 Chris_Rands(上面的评论)。设置操作:
set(f) - set(x)
。对于较大的列表可能更有效但不保留顺序。 Gredit 转到 mpf82. This also removes duplicates inf
, as pointed out by asongtoruin.