2个列表之间的唯一值 [英] unique values between 2 lists

查看:65
本文介绍了2个列表之间的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找b/w 2列表的唯一值,但是这种逻辑似乎不起作用

I am trying to find unique values b/w 2 lists but this logic doesn't seems to work

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]

仅从两个列表python中获取唯一元素

同样在这里问 解决方案:

same ask here solution:

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未输出,我需要

as you can see its adding 1,2,3,4 not output I need

推荐答案

在关闭和重新打开所有麻烦之后,我觉得有人应该真正回答这个问题.

After all the hassle with closing and re-opening I feel someone ought to actually answer the question.

有多种方法可以达到预期效果:

There are different ways to achieve the desired result:

  1. 列表理解:[i for i in f if i not in x].效率可能较低,但可以保留顺序.功劳归 Chris_Rands (上面的评论).

  1. List comprehensions: [i for i in f if i not in x]. Maybe less efficient but preserves order. Credit goes to Chris_Rands (comment above).

设置操作:set(f) - set(x).对于较大的列表,可能更有效,但不会保留顺序. Gredit转到 mpf82 .正如 asongtoruin 指出的那样,这也会删除f中的重复项.

Set operations: set(f) - set(x). Likely more efficient for larger lists but does not preserve order. Gredit goes to mpf82. This also removes duplicates in f, as pointed out by asongtoruin.

这篇关于2个列表之间的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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