0

I got the following value in my list :


     A= [{'43c776cc-dcfe-498e-9e0c-465e498c4509'},
    {'43c776cc-dcfe-498e-9e0c-465e498c4509'},
    {'43c776cc-dcfe-498e-9e0c-465e498c4509'},
    {'fbcbdda3-e391-42f0-b139-c266c0bd564d'},
    {'fbcbdda3-e391-42f0-b139-c266c0bd564d'},
    {'43c776cc-dcfe-498e-9e0c-465e498c4509'},
    {'43c776cc-dcfe-498e-9e0c-465e498c4509'},
    {'43c776cc-dcfe-498e-9e0c-465e498c4509'}]

How can I get only unique value ==> two in that example.

Thanks

  • 1
    Why a list of sets `A=[{''},{''}]` and not simply a list of strings `A=['','']`? Then you could simply use `set(A)` to obtain unique values – SevC_10 Apr 08 '21 at 10:42
  • In case there is just one element in each set: `set([list(x)[0] for x in A])` – Maurice Meyer Apr 08 '21 at 10:49

3 Answers3

0

Assuming that you really do want each element to be a set containing a single string, rather than a single string, you could do something slightly unwieldy like this:

A = [set(x) for x in set([tuple(x) for x in A])]

I would really question why you wanted this though, especially if they are single strings.

If you just had a list of strings, though, the solution is much simpler, as mentioned in a comment above:

A = list(set(A))

SDS0
  • 500
  • 2
  • 8
0

You can iterate over the sets in your list and union them in a new set then convert it to a list. Personally I would prefer to use reduce function and just union the sets in one line. Both give the same result but personally i like the second way via reduce.


sets_list = [{'43c776cc-dcfe-498e-9e0c-465e498c4509'},
             {'43c776cc-dcfe-498e-9e0c-465e498c4509'},
             {'43c776cc-dcfe-498e-9e0c-465e498c4509'},
             {'fbcbdda3-e391-42f0-b139-c266c0bd564d'},
             {'fbcbdda3-e391-42f0-b139-c266c0bd564d'},
             {'43c776cc-dcfe-498e-9e0c-465e498c4509'},
             {'43c776cc-dcfe-498e-9e0c-465e498c4509'},
             {'43c776cc-dcfe-498e-9e0c-465e498c4509'}]

# using a loop
my_set = set()
for _set in sets_list:
    my_set |= _set
print("loop:", list(my_set))

# using reduce function
from functools import reduce
print("reduce:", list(reduce(lambda set_a, set_b: set_a | set_b, sets_list)))

OUTPUT

loop: ['43c776cc-dcfe-498e-9e0c-465e498c4509', 'fbcbdda3-e391-42f0-b139-c266c0bd564d']
reduce: ['43c776cc-dcfe-498e-9e0c-465e498c4509', 'fbcbdda3-e391-42f0-b139-c266c0bd564d']
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42
0

A more complicated one liner if your list elements are always sets

list(set(sum(map(list, A),[]))).

The sum(map(list, A), []) will convert and merge all the individual sets into a single list, then applying list(set()) will give you the list of unique values.

naveen namani
  • 152
  • 1
  • 11