さまざまな要素を含む同じ長さの 2 つのリストがあります。それらを比較して、両方のリストに存在する要素の数を見つけようとしていますが、インデックスが異なります。
私が何を意味するかを示すために、入力/出力の例をいくつか示します。
>>> compare([1, 2, 3, 4], [4, 3, 2, 1])
4
>>> compare([1, 2, 3], [1, 2, 3])
0
# Each item in the first list has the same index in the other
>>> compare([1, 2, 4, 4], [1, 4, 4, 2])
2
# The 3rd '4' in both lists don't count, since they have the same indexes
>>> compare([1, 2, 3, 3], [5, 3, 5, 5])
1
# Duplicates don't count
リストは常に同じサイズです。
これは私がこれまでに持っているアルゴリズムです:
def compare(list1, list2):
# Eliminate any direct matches
list1 = [a for (a, b) in zip(list1, list2) if a != b]
list2 = [b for (a, b) in zip(list1, list2) if a != b]
out = 0
for possible in list1:
if possible in list2:
index = list2.index(possible)
del list2[index]
out += 1
return out
同じことを行うためのより簡潔で雄弁な方法はありますか?