Find matches between many lists of the same length at the same position

I have two lists (maybe more recent ones) and I want to figure out which mach values are in the same position.

This code below returns matched values, but does not return the position of the match.

a = [5,0]
b = [5,1]

print list(set(a).intersection(set(b)))

>>5

      

+3


source to share


6 answers


Use zip

and enumerate

and check for unique values:



lists = [a, b] # add more lists here if need be...
for idx, items in enumerate(zip(*lists)):
    unique = set(items)
    if len(unique) == 1:
        # idx = position, unique.pop() == the value
        print idx, unique.pop()

      

+4


source


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


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


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


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


This is the answer for as many lists as you want to use

a = [5,0,1,2]
b = [5,2,3,2]
lists = [a,b,b,a,a]
d = dict()
for l in lists:
    for i in range(len(a)):
        if i not in d.keys():
            d[i] = a[i]
        elif d[i] != l[i]:
            d[i] = -1
for i in d.keys():
    if d[i] != -1:
        print d[i], i

      

0


source







All Articles