Get unique values in List of Lists in python

前端 未结 6 1413
北海茫月
北海茫月 2020-12-05 13:35

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\'         


        
相关标签:
6条回答
  • 2020-12-05 14:15
    array = [['a','b'], ['a', 'b','c'], ['a']]
    result = set(x for l in array for x in l)
    
    0 讨论(0)
  • 2020-12-05 14:15

    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)))
    
    0 讨论(0)
  • 2020-12-05 14:15

    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:

    unique_values = [list(x) for x in set(tuple(x) for x in aList)]
    
    0 讨论(0)
  • 2020-12-05 14:27

    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']
    
    0 讨论(0)
  • 2020-12-05 14:33
    array = [['a','b'], ['a', 'b','c'], ['a']]
    unique_values = list(reduce(lambda i, j: set(i) | set(j), array))
    
    0 讨论(0)
  • 2020-12-05 14:39

    You can use numpy.unique:

    import numpy
    import operator
    print numpy.unique(reduce(operator.add, [['a','b'], ['a', 'b','c'], ['a']]))
    # ['a' 'b' 'c']
    
    0 讨论(0)
提交回复
热议问题