从 Python 列表中仅检索非重复元素的最佳选项是什么?假设我有以下列表:
lst = [1, 2, 3, 2, 3, 4]
我想检索以下内容:
lst = [1, 4]
(2
and 3
在该列表中不是唯一的,因此不会检索到它们)
Use collections.Counter http://docs.python.org/2/library/collections.html#collections.Counter获取项目数量。与列表理解相结合,仅保留那些计数为 1 的内容。
>>> from collections import Counter
>>> lst = [1, 2, 3, 2, 3, 4]
>>> [item for item, count in Counter(lst).items() if count == 1]
[1, 4]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)