从python中的列表中获取唯一值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12897374/
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
Get unique values from a list in python
提问by savitha
I want to get the unique values from the following list:
我想从以下列表中获取唯一值:
['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
The output which I require is:
我需要的输出是:
['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']
This code works:
此代码有效:
output = []
for x in trends:
if x not in output:
output.append(x)
print(output)
is there a better solution I should use?
我应该使用更好的解决方案吗?
回答by Samuele Mattiuzzo
What type is your output variable?
你的输出变量是什么类型?
Python setsare what you need. Declare output like this:
Python集正是您所需要的。像这样声明输出:
output = set() # initialize an empty set
and you're ready to go adding elements with output.add(elem)and be sure they're unique.
并且您已准备好添加元素output.add(elem)并确保它们是独一无二的。
Warning: sets DO NOT preserve the original order of the list.
警告:集合不保留列表的原始顺序。
回答by lefterav
First declare your list properly, separated by commas. You can get the unique values by converting the list to a set.
首先正确声明您的列表,用逗号分隔。您可以通过将列表转换为集合来获取唯一值。
mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
myset = set(mylist)
print(myset)
If you use it further as a list, you should convert it back to a list by doing:
如果您进一步将其用作列表,则应通过执行以下操作将其转换回列表:
mynewlist = list(myset)
Another possibility, probably faster would be to use a set from the beginning, instead of a list. Then your code should be:
另一种可能更快的可能性是从一开始就使用一个集合,而不是一个列表。那么你的代码应该是:
output = set()
for x in trends:
output.add(x)
print(output)
As it has been pointed out, sets do not maintain the original order. If you need that, you should look for an ordered setimplementation (see this questionfor more).
回答by Nicolas Barbey
A Python list:
一个 Python 列表:
>>> a = ['a', 'b', 'c', 'd', 'b']
To get unique items, just transform it into a set (which you can transform back again into a list if required):
要获得独特的物品,只需将其转换为一个集合(如果需要,您可以再次将其转换回列表):
>>> b = set(a)
>>> print(b)
{'b', 'c', 'd', 'a'}
回答by Senthil Kumaran
First thing, the example you gave is not a valid list.
首先,您给出的示例不是有效列表。
example_list = [u'nowplaying',u'PBS', u'PBS', u'nowplaying', u'job', u'debate',u'thenandnow']
Suppose if above is the example list. Then you can use the following recipe as give the itertools example doc that can return the unique values and preserving the order as you seem to require. The iterable here is the example_list
假设上面是示例列表。然后,您可以使用以下配方作为 itertools 示例文档,该文档可以返回唯一值并根据您的需要保留顺序。这里的迭代是example_list
from itertools import ifilterfalse
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in ifilterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
回答by Sanjar Stone
- At the begin of your code just declare your output list as empty:
output=[] - Instead of your code you may use this code
trends=list(set(trends))
- 在代码的开头,只需将输出列表声明为空:
output=[] - 您可以使用此代码代替您的代码
trends=list(set(trends))
回答by Ricky Wilson
def setlist(lst=[]):
return list(set(lst))
回答by CreamStat
Try this function, it's similar to your code but it's a dynamic range.
试试这个函数,它与您的代码类似,但它是一个动态范围。
def unique(a):
k=0
while k < len(a):
if a[k] in a[k+1:]:
a.pop(k)
else:
k=k+1
return a
回答by alemol
To be consistent with the type I would use:
为了与我将使用的类型保持一致:
mylist = list(set(mylist))
回答by DeeCee
Use the following function:
使用以下函数:
def uniquefy_list(input_list):
"""
This function takes a list as input and return a list containing only unique elements from the input list
"""
output_list=[]
for elm123 in input_list:
in_both_lists=0
for elm234 in output_list:
if elm123 == elm234:
in_both_lists=1
break
if in_both_lists == 0:
output_list.append(elm123)
return output_list
回答by MultiTeemer
set - unordered collection of unique elements. List of elements can be passed to set's constructor. So, pass list with duplicate elements, we get set with unique elements and transform it back to list then get list with unique elements. I can say nothing about performance and memory overhead, but I hope, it's not so important with small lists.
set - 唯一元素的无序集合。元素列表可以传递给集合的构造函数。因此,传递具有重复元素的列表,我们使用唯一元素设置并将其转换回列表,然后获取具有唯一元素的列表。我对性能和内存开销无话可说,但我希望,对于小列表来说,这不是那么重要。
list(set(my_not_unique_list))
Simply and short.
简单而简短。

