在python中的列表列表中获取唯一值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30565759/
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 in List of Lists in python
提问by mihasa
I want to create a list (or set) of all unique values appearing in a list of lists in python. I have something like this:
我想创建一个列表(或集合),其中包含出现在 python 列表列表中的所有唯一值。我有这样的事情:
aList=[['a','b'], ['a', 'b','c'], ['a']]
and i would like the following:
我想要以下内容:
unique_values=['a','b','c']
I know that for a list of strings you can just use set(aList), but I can't figure how to solve this in a list of lists, since set(aList) gets me the error message
我知道对于字符串列表,您可以只使用 set(aList),但我不知道如何在列表列表中解决这个问题,因为 set(aList) 给了我错误消息
unhashable type: 'list'
How can i solve it?
我该如何解决?
采纳答案by dlask
array = [['a','b'], ['a', 'b','c'], ['a']]
result = set(x for l in array for x in l)
回答by no coder
array = [['a','b'], ['a', 'b','c'], ['a']]
unique_values = list(reduce(lambda i, j: set(i) | set(j), array))
回答by Tanveer Alam
回答by alfasin
You can use numpy.unique:
您可以使用numpy.unique:
import numpy
import operator
print numpy.unique(reduce(operator.add, [['a','b'], ['a', 'b','c'], ['a']]))
# ['a' 'b' 'c']
回答by Haresh Shyara
Try to this.
试试这个。
array = [['a','b'], ['a', 'b','c'], ['a']]
res=()
for item in array:
res = list(set(res) | set(item))
print res
Output:
输出:
['a', 'c', 'b']
回答by Charly Empereur-mot
The 2 top voted answers did not work for me, I'm not sure why (but I have integer lists). In the end I'm doing this:
2 个最高投票的答案对我不起作用,我不知道为什么(但我有整数列表)。最后我这样做:
unique_values = [list(x) for x in set(tuple(x) for x in aList)]