I have 2d array like this
arry = [[6,5,7,8],[2,5,5,6]]
The first two values are x,y are points in graph. I want the sorted array based on the points i give for search. So, if i give [3,5] Since this is close to [2,5] i need to get [[2,5,5,6],[6,5,7,8]]
Thanks in advance !
Another example
[[6, 6, 8, 10], [3, 3, 8, 10], [15, 15, 8, 10]]
If i give [16,16], we should get
[[15, 15, 8, 10], [6, 6, 8, 10], [3, 3, 8, 10]]
CodePudding user response:
IIUC you want to sort your sublist based on the minimum difference from a reference list.
You could use sorted
and its key
parameter.
If you need to take the minimum difference in order of the points:
sorted(l, key=lambda e: [abs(a-b) for a,b in zip(e, [2,5])])
output: [[2, 5, 5, 6], [6, 5, 7, 8]]
If you want the euclidean distance (makes more sense from a geometrical perspective as this is the length of a straight line between the points), you need to take the sum of the square difference:
sorted(l, key=lambda e: sum((a-b)**2 for a,b in zip(e, [2,5])))
output: [[2, 5, 5, 6], [6, 5, 7, 8]]
NB. I am not computing the square root here are the squares and their roots are ordered the same
NB2. if you want to make thinks multi-dimensional, just add more value in zip
, for example: zip(e, [2,5,4])
CodePudding user response:
Use a list comprehension to get distances (I'm using Euclidian distances here):
data = [[6,5,7,8],[2,5,5,6]]
query = [3,5]
distances = [pow(sample[0]-query[0],2) pow(sample[1]-query[1],2) for sample in data]
# No need to calculate roots i.e actual distance as you just need to compare
Then you can sort the data by distances using:
sorted_data = [x for _, x in sorted(zip(distances, data))]
Doing this you get sorted_data = [[2, 5, 5, 6], [6, 5, 7, 8]]