I want to find any pair of elements in a list that have the same attribute. For example,
class X:
def __init__(self, param):
self.param = param
my_list = [X(1), X(2), X(3), X(2), X(3), X(3)]
So if comparing on x.param
, I'd be looking for my_list[1], my_list[3]
or my_list[2], my_list[4]
or my_list[2], my_list[5]
or my_list[4], my_list[5]
. However, there's no guarantee that the list would necessary have any elements with the same property, e.g.
my_list = [X(1), X(2), X(3)]
might also be a valid parameter to this function.
The obvious way to do this seems to be:
def find_dupe(my_list, my_lambda):
attrs = dict()
for item in my_list:
if my_lambda(item) in attrs:
return [attrs[my_lambda(item)], item]
attrs[my_lambda(item)] = item
return []
But it seems a bit inelegant and I'm wondering if there's a nicer way to do this.