Tanay Soni Tanay Soni - 5 months ago 32
Python Question

Python: find most common element in corresponding two lists

I have two lists holding x and y co-ordinates of points where each corresponding element represents a point.

Just an example, X_List = [1, 3, 1, 4], Y_List = [6, 7, 6, 1] then points are (1,6) (3,7) (1,6) (4,1). Thus, the most common point is (1,6).

Here's my code:

Points=[]
for x,y in zip(X_List, Y_List):
Points.append([x,y])
MostCommonPoint = max(set(Points), key=Points.count)


But, this will not work work as Points in a list which is unhashable type.

Answer

First, zip returns a list of tuples (or an iterator of tuples in Python 3). That means you could just use zip(X_List, Y_List) instead of Points (or list(zip(X_List, Y_List)) on Python 3), and your code would work. However, it would take quadratic time.

A faster way is to use a collections.Counter, which is a dict subclass designed for counting things:

import collections

# Produce a Counter mapping each point to how many times it appears.
counts = collections.Counter(zip(X_List, Y_List))

# Find the point with the highest count.
MostCommonPoint = max(counts, key=counts.get)