2个列表之间的唯一值

编程入门 行业动态 更新时间:2024-10-09 11:20:33
本文介绍了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:

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

  • 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个列表之间的唯一值

    本文发布于:2023-11-30 15:40:55,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1650542.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:列表   唯一值

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!