Get unique values in List of Lists in python

2019-01-18 10:59发布

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:

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

unhashable type: 'list'

How can i solve it?

5条回答
Evening l夕情丶
2楼-- · 2019-01-18 11:12
array = [['a','b'], ['a', 'b','c'], ['a']]
unique_values = list(reduce(lambda i, j: set(i) | set(j), array))
查看更多
女痞
3楼-- · 2019-01-18 11:17

You can use itertools's chain to flatten your array and then call set on it:

from itertools import chain

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

If you are expecting a list object:

print list(set(chain(*array)))
查看更多
爷、活的狠高调
4楼-- · 2019-01-18 11:17

You can use numpy.unique:

import numpy
import operator
print numpy.unique(reduce(operator.add, [['a','b'], ['a', 'b','c'], ['a']]))
# ['a' 'b' 'c']
查看更多
欢心
5楼-- · 2019-01-18 11:17

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']
查看更多
我想做一个坏孩纸
6楼-- · 2019-01-18 11:22
array = [['a','b'], ['a', 'b','c'], ['a']]
result = set(x for l in array for x in l)
查看更多
登录 后发表回答