仅从列表中检索非重复元素 [英] Retrieve only non-duplicate elements from a list
本文介绍了仅从列表中检索非重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从 Python 列表中仅检索非重复元素的最佳选择是什么?假设我有以下列表:
lst = [1, 2, 3, 2, 3, 4]
我想检索以下内容:
lst = [1, 4]
(2
和 3
在该列表中不是唯一的,因此它们不会被检索到)
解决方案
使用 列表理解:
<预><代码>>>>lst = [1, 2, 3, 2, 3, 4]>>>[x for x in lst if lst.count(x) == 1][1, 4]>>>另外,我建议你不要命名一个变量list
——它掩盖了内置变量.
What is the best option to retrieve only non-duplicate elements from a Python list? Say I have the following list:
lst = [1, 2, 3, 2, 3, 4]
I would like to retrieve the following:
lst = [1, 4]
(2
and 3
are not unique in that list, so they don't get retrieved)
解决方案
This is a breeze with a list comprehension:
>>> lst = [1, 2, 3, 2, 3, 4]
>>> [x for x in lst if lst.count(x) == 1]
[1, 4]
>>>
Also, I recommend that you do not name a variable list
--it overshadows the built-in.
这篇关于仅从列表中检索非重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文