Find matches between many lists of the same length at the same position
6 answers
def check_equal(lst):
return lst[1:] == lst[:-1]
def get_position_and_matches(*lists):
shortest_list = min(lists, key=len)
for index,item in enumerate(shortest_list):
matching = [l[index] for l in lists]
if check_equal(matching):
print "Index: {0}, Value: {1}".format(index, shortest_list[index])
one = [1, 3, 4, 6, 2]
two = [1, 3, 4, 2, 9, 9]
three = [2, 3, 4]
get_position_and_matches(one, two, three)
+2
source to share
You can write your own method:
a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]
c = [3, 3, 3, 3, 3]
allLists = [b, c] # all lists but the first
for i in range(len(a)):
good = True
for l in allLists:
if l[i] != a[i]:
good = False
break
if good:
print(i, a[i])
edited to make it easier to add more lists
+1
source to share
This will show you the position of the match (if None is not a valid element)
a=[1,2,3]
b=[0,2,3]
c=[3,2,1]
l = [a, b, c] # add any number of lists
z = zip(*l)
pos = 0
for i in z:
if reduce(lambda x, y: x if x == y else None, i):
print pos
pos += 1
or, if you want to keep a match for each position:
matches=[reduce(lambda x, y: x if x == y else None, i) for i in z]
will create
[None, 2, None]
+1
source to share
matching_indexes = [i for i in range(len(a)) if a[i] == b[i] == c[i]]
Can be used. Easy list comprehension to check each individual value of a, b and c. More or less ==
can be added for each compared list. However, this assumes that all lists are the same length, or that a is the shortest list.
0
source to share