I'm currently looking for a way to compare elements of a list to one another going from left to right.
Here is my list:
mylist = [[15], [14, 15], [19, 20], [13], [3], [65, 19], [19, 20, 31]]
I need to compare the first element to all others and check if any of the values match, same thing for the second and third element and so on until it reaches the end of the list. If there is a match, I need to print it out. I need to print out the value that has match and the index that it matched at.
For example.
index 0 matched with index 1 for value 15.
index 2 matched with index 5 for value 19
index 2 matched with index 6 for value 19
index 2 matched with index 6 for value 20
index 5 matched with index 6 for value 19.
How can I go about doing this?
解决方案mylist = [[15], [14, 15], [19, 20], [13], [3], [65, 19], [19, 20, 31]]
my_set_list = [set(item) for item in mylist]
for i1, item in enumerate(my_set_list):
for i2 in xrange(i1 + 1, len(my_set_list)):
for val in (item & my_set_list[i2]):
print "Index {} matched with index {} for value {}".format(i1,i2,val)
Output
Index 0 matched with index 1 for value 15.
Index 2 matched with index 5 for value 19.
Index 2 matched with index 6 for value 19.
Index 2 matched with index 6 for value 20.
Index 5 matched with index 6 for value 19.