在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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:39:25  来源:igfitidea点击:

Get unique values in List of Lists in python

pythonlistsetunique

提问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

You can use itertools's chainto flatten your array and then call seton it:

您可以使用itertools'schain来展平您的数组,然后调用set它:

from itertools import chain

array = [['a','b'], ['a', 'b','c'], ['a']]
print set(chain(*array))

If you are expecting a listobject:

如果你期待一个list对象:

print list(set(chain(*array)))

回答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)]