Python - Generic Lists Among Lists in a List
I need to find the first shared list (which is a list of coordinates in this case) between a variable number of lists.
i.e. this list
>>> [[[1,2],[3,4],[6,7]],[[3,4],[5,9],[8,3],[4,2]],[[3,4],[9,9]]]
should return
>>> [3,4]
To put it simply, I can work with a list of all common lists (coordinates) between lists containing coordinates.
I cannot use sets or dictionaries because lists are not hashed (I guess?).
source to share
Correct, list
objects are not hashed because they are mutable. tuple
objects are hashed (assuming all their elements are hashed). Since your innermost lists are just integers, this is a great way to get around the inappropriateness of lists:
>>> lists = [[[1,2],[3,4],[6,7]],[[3,4],[5,9],[8,3],[4,2]],[[3,4],[9,9]]]
>>> sets = [set(tuple(x) for x in y) for y in lists]
>>> set.intersection(*sets)
set([(3, 4)])
Here I am giving you a set that contains tuples of coordinates that are present in all sublists. To get a list of lists like you started with:
[list(x) for x in set.intersection(*sets)]
does the trick.
To fix the problem with @wim, if you really want to reference the first element in the intersection (where the first
first one is defined in lists[0]
), the easiest way is probably like this:
#... Stuff as before
intersection = set.intersection(*sets)
reference_to_first = next( (x for x in lists[0] if tuple(x) in intersection), None )
This returns None
if the intersection is empty.
source to share
Solution with recursive function. :)
This gets the first duplicated item.
def get_duplicated_element(array):
global result, checked_elements
checked_elements = []
result = -1
def array_recursive_check(array):
global result, checked_elements
if result != -1: return
for i in array:
if type(i) == list:
if i in checked_elements:
result = i
return
checked_elements.append(i)
array_recursive_check(i)
array_recursive_check(array)
return result
get_duplicated_element([[[1,2],[3,4],[6,7]],[[3,4],[5,9],[8,3],[4,2]],[[3,4],[9,9]]])
[3, 4]
source to share