python - How to find elements existing in two lists but with different indexes -
i have 2 lists of same length contains variety of different elements. i'm trying compare them find number of elements exist in both lists, have different indexes.
here example inputs/outputs demonstrate mean:
>>> compare([1, 2, 3, 4], [4, 3, 2, 1]) 4 >>> compare([1, 2, 3], [1, 2, 3]) 0 # each item in first list has same index in other >>> compare([1, 2, 4, 4], [1, 4, 4, 2]) 2 # 3rd '4' in both lists don't count, since have same indexes >>> compare([1, 2, 3, 3], [5, 3, 5, 5]) 1 # duplicates don't count
the lists same size.
this algorithm have far:
def compare(list1, list2): # eliminate direct matches list1 = [a (a, b) in zip(list1, list2) if != b] list2 = [b (a, b) in zip(list1, list2) if != b] out = 0 possible in list1: if possible in list2: index = list2.index(possible) del list2[index] out += 1 return out
is there more concise , eloquent way same thing?
this python function hold examples provided:
def compare(list1, list2): d = {e:i i, e in enumerate(list1)} return len(set(e i, e in enumerate(list2) if d.get(e) not in (none, i)))
Comments
Post a Comment