0

I have two list.


    red = [[2,2], [2, 3], [2, 4], [3, 2], [3, 3], [3, 4], [4, 2], [4, 3], [4, 4]]
    
    blue = [[3, 3], [3, 4], [3, 5], [3, 6], [4, 3], [4, 4], [4, 5], [4, 6], [5, 3], [5, 4], [5, 5], [5, 6], [6, 3], [6, 4], [6, 5], [6, 6]]

how to find intersection in this case?

I know what is the set.

but, In this case... I think it can not to do to use list.

list in list... how can i do?


[[2, 2], [2, 3], [2, 4], [3, 2], [3, 3], [3, 4], [4, 2], [4, 3], [4, 4]]
[[3, 3], [3, 4], [3, 5], [3, 6], [4, 3], [4, 4], [4, 5], [4, 6], [5, 3], [5, 4], [5, 5], [5, 6], [6, 3], [6, 4], [6, 5], [6, 6]]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-46-e0a8e962ef62> in <module>()
     11     print(list(red))
     12     print(list(blue))
---> 13     intersection = len(list(set(red) & set(blue)))
     14     print(list(set(red) & set(blue)))
     15     print(set(list(red)) & set(list(blue)))

TypeError: unhashable type: 'list'
yamma
  • 11
  • 1
    Does this answer your question? [Intersection of subelements of multiple list of lists in dictionary](https://stackoverflow.com/questions/28145319/intersection-of-subelements-of-multiple-list-of-lists-in-dictionary) [that's about values in a dict; but the values are lists of lists, so it's pretty similar] – Nelewout Mar 29 '22 at 15:47
  • To Nelewout // WOWOWOWOWOW you guys are so kind... I'm deeply touched... – yamma Mar 29 '22 at 16:07

1 Answers1

1

Sets can only contain hashable data, and lists are not hashable since they're mutable. On the other hand, tuples are perfectly hashable.

red_set = frozenset(tuple(x) for x in red)
blue_set = frozenset(tuple(x) for x in blue)

intersection_set = red_set & blue_set
intersection_list = list(list(x) for x in intersection_set)

If you don't mind working with tuples, you can leave it in the form intersection_set and it'll work just fine. But the last line gets it back to the original "list of lists" representation you started with.

Note that set would work here too, but since we never change them, frozenset states our intentions a bit better.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • wow... really thank you... actually I didn't know "frozenset"... sosososo kind!! have a nice day!! – yamma Mar 29 '22 at 16:00