0

I have a list of sets:

list = [{1,2}, {2,3}, {1,3}, {2,1} etc]

I need a list where every element appears once. creating a set of the list fails with a set is not hashable error If I create another list, and add every element once with if not in list then append list works, but now I have to deal with a list with aroun 600 000 value pairs, and it takes forever. Is there a more efficent way?

biohazard90
  • 95
  • 1
  • 7
  • 1
    What about using `set(map(tuple, list_))`? – S3DEV Nov 19 '20 at 12:06
  • it fails with map() must have at least two arguments. if i add another empty list, it returns an empty list – biohazard90 Nov 19 '20 at 12:08
  • 3
    Given the answer by @AntoineDubuis - can you please clarify the desired output. My my understanding of 'unique element' refers to a set of `{1, 2}` - whereas the answer provided returns unique individual values. – S3DEV Nov 19 '20 at 12:09
  • well, since these are sets, from list = [{1,2}, {2,3}, {1,3}, {2,1}] I need one of the {1,2} elements removed I need only the unique pairs, without directions or position so the output would be: result_list = [{1,2}, {2,3}, {1,3}] – biohazard90 Nov 19 '20 at 12:10
  • It has two elements, `tuple` and your list. I used `list_` as your variable `list` is overwriting the built-in. – S3DEV Nov 19 '20 at 12:10
  • 2
    @biohazard90 Do you need output as a list that contains unique "sets" or unique "single values"? Meaning, for a set `{1, 2}` is the same as `{2, 1}`, so considering your input, is your output supposed to be `{1, 2, 3}` or `[{1, 2}, {2, 3}, {1, 3}]`? – ChatterOne Nov 19 '20 at 12:12
  • @ChatterOne A list that contains unique "sets" I think what S3DEV suggested actually worked, but if you have another solution feel free to share – biohazard90 Nov 19 '20 at 12:19
  • You can use `set(map(frozenset, data))` – juanpa.arrivillaga Nov 19 '20 at 12:27

2 Answers2

2

Referencing your comment; as you mentioned this worked, I'll post my comment as a proper answer.

set(map(tuple, list_))

Output:

{(1, 2), (1, 3), (2, 3)}

Please note:
I've changed the your list variable named to list_, as it was overwriting the built-in.

This method appears to scale linearly. Time over a list of 1000 sets was 206 us and 10000 was 2.19 ms.

S3DEV
  • 8,768
  • 3
  • 31
  • 42
  • If i understand this correctly: the problem is that sets are not hashable. To get around the problem, we use the map function, which creates a tuple of every single sets, thus it will be hashable (since the set becomes an immutable tuple) and then it can be passed into the set function right? – biohazard90 Nov 19 '20 at 12:28
  • Yep. [This SO post](https://stackoverflow.com/a/6310901/6340496), which quotes the docs, clarifies it nicely. Glad it's working for you. – S3DEV Nov 19 '20 at 12:57
1

You can use the following method to perform a union on a list of set:

l = [{1,2}, {2,3}, {1,3}, {2,1}]
set.union(*l)

output:

{1, 2, 3}
Antoine Dubuis
  • 4,974
  • 1
  • 15
  • 29