如何使列表只包含 Python 中的不同元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4459703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make lists contain only distinct element in Python?
提问by Alex
I have a list in Python, how can I make it's values unique?
我在 Python 中有一个列表,如何使其值唯一?
采纳答案by Mark Byers
The simplest is to convert to a set then back to a list:
最简单的方法是转换为一个集合,然后再转换回一个列表:
my_list = list(set(my_list))
One disadvantage with this is that it won't preserve the order. You may also want to consider if a set would be a better data structure to use in the first place, instead of a list.
这样做的一个缺点是它不会保留顺序。您可能还想首先考虑集合是否是更好的数据结构,而不是列表。
回答by sje397
From http://www.peterbe.com/plog/uniqifiers-benchmark:
从http://www.peterbe.com/plog/uniqifiers-benchmark:
def f5(seq, idfun=None):
# order preserving
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
回答by khachik
To preserve the order:
要保留顺序:
l = [1, 1, 2, 2, 3]
result = list()
map(lambda x: not x in result and result.append(x), l)
result
# [1, 2, 3]
回答by Seitaridis
If all elements of the list may be used as dictionary keys (i.e. they are all hashable) this is often faster. Python Programming FAQ
如果列表的所有元素都可以用作字典键(即它们都是可散列的),这通常会更快。Python 编程常见问题
d = {}
for x in mylist:
d[x] = 1
mylist = list(d.keys())
回答by Pawe? Pra?ak
Modified versions of http://www.peterbe.com/plog/uniqifiers-benchmark
http://www.peterbe.com/plog/uniqifiers-benchmark 的修改版本
To preserve the order:
要保留顺序:
def f(seq): # Order preserving
''' Modified version of Dave Kirby solution '''
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)]
OK, now how does it work, because it's a little bit tricky here if x not in seen and not seen.add(x):
好的,现在它是如何工作的,因为这里有点棘手if x not in seen and not seen.add(x):
In [1]: 0 not in [1,2,3] and not print('add')
add
Out[1]: True
Why does it return True? print (and set.add) returns nothing:
为什么它返回True?打印(和 set.add)不返回任何内容:
In [3]: type(seen.add(10))
Out[3]: <type 'NoneType'>
and not None == True, but:
和not None == True,但是:
In [2]: 1 not in [1,2,3] and not print('add')
Out[2]: False
Why does it print 'add' in [1] but not in [2]? See False and print('add'), and doesn't check the second argument, because it already knows the answer, and returns true only if both arguments are True.
为什么它在 [1] 中打印 'add' 而在 [2] 中不打印?See False and print('add'),并且不检查第二个参数,因为它已经知道答案,并且仅当两个参数都为 True 时才返回 true。
More generic version, more readable, generator based, adds the ability to transform values with a function:
更通用的版本,更具可读性,基于生成器,增加了使用函数转换值的能力:
def f(seq, idfun=None): # Order preserving
return list(_f(seq, idfun))
def _f(seq, idfun=None):
''' Originally proposed by Andrew Dalke '''
seen = set()
if idfun is None:
for x in seq:
if x not in seen:
seen.add(x)
yield x
else:
for x in seq:
x = idfun(x)
if x not in seen:
seen.add(x)
yield x
Without order (it's faster):
没有订单(它更快):
def f(seq): # Not order preserving
return list(set(seq))
回答by adam.lofts
The simplest way to remove duplicates whilst preserving order is to use collections.OrderedDict(Python 2.7+).
在保留顺序的同时删除重复项的最简单方法是使用collections.OrderedDict(Python 2.7+)。
from collections import OrderedDict
d = OrderedDict()
for x in mylist:
d[x] = True
print d.iterkeys()
回答by cod3monk3y
How about dictionary comprehensions?
如何解释内涵?
>>> mylist = [3, 2, 1, 3, 4, 4, 4, 5, 5, 3]
>>> {x:1 for x in mylist}.keys()
[1, 2, 3, 4, 5]
EDITTo @Danny's comment: my original suggestion does not keep the keys ordered. If you need the keys sorted, try:
编辑@Danny 的评论:我最初的建议没有按顺序排列钥匙。如果您需要对键进行排序,请尝试:
>>> from collections import OrderedDict
>>> OrderedDict( (x,1) for x in mylist ).keys()
[3, 2, 1, 4, 5]
which keeps elements in the order by the first occurrence of the element (not extensively tested)
它按元素第一次出现的顺序保持元素(未经广泛测试)
回答by brillout
one-liner and preserve order
单线并保留订单
list(OrderedDict.fromkeys([2,1,1,3]))
although you'll need
虽然你需要
from collections import OrderedDict
回答by disp_name
Let me explain to you by an example:
我举个例子给大家解释一下:
if you have Python list
如果你有 Python 列表
>>> randomList = ["a","f", "b", "c", "d", "a", "c", "e", "d", "f", "e"]
and you want to remove duplicates from it.
并且您想从中删除重复项。
>>> uniqueList = []
>>> for letter in randomList:
if letter not in uniqueList:
uniqueList.append(letter)
>>> uniqueList
['a', 'f', 'b', 'c', 'd', 'e']
This is how you can remove duplicates from the list.
这是您可以从列表中删除重复项的方法。
回答by Tung Nguyen
The characteristics of sets in Python are that the data items in a set are unordered and duplicates are not allowed. If you try to add a data item to a set that already contains the data item, Python simply ignores it.
Python中集合的特点是集合中的数据项是无序的,不允许重复。如果您尝试将数据项添加到已经包含该数据项的集合中,Python 会简单地忽略它。
>>> l = ['a', 'a', 'bb', 'b', 'c', 'c', '10', '10', '8','8', 10, 10, 6, 10, 11.2, 11.2, 11, 11]
>>> distinct_l = set(l)
>>> print(distinct_l)
set(['a', '10', 'c', 'b', 6, 'bb', 10, 11, 11.2, '8'])

