# how to sort a list of tuples with custom function

```i tried with
testing1.sort(key=lambda x: x[0])
but only first element of tuple are grouped

then i expect to sort with custom function if difference between first element of tuple and another first element of tuple is less than some value
and do for second element too,

goal to segmentation of black words from photo

from PIL import Image
from functools import partial
ma = Image.open("roster.png")
print ma.size
print color1[1,1]
print ma.size
print color1[1,1]
colortolocation = {}
k = key1
if k in keyandmemory:
keyandmemory[k].append(memorycontent)
else:
keyandmemory[k] = [memorycontent]
return keyandmemory

for ii in range(0, ma.size[0]):
for jj in range(0, ma.size[1]):

def isneighborlocation(lo1, lo2):
if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
return 1
elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
return 1
elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
return 1
else:
return 0

for eachcolor in colortolocation:
testing1 = list(colortolocation[eachcolor])
#testing1.sort(key=lambda x: x[1])
#custom_list_indices = {v: i for i, v in enumerate(custom_list)}
testing1.sort(key=lambda x: x[0]-x[1])
locations = testing1
locationsgroup = {}
continueconnect = 0
for ii in range(0,len(locations)-1):
if isneighborlocation(locations[ii], locations[ii+1]) == 1:
if continueconnect == 0:
keyone = len(locationsgroup)+1
if keyone in locationsgroup:
if locations[ii] not in locationsgroup[keyone]:
if locations[ii+1] not in locationsgroup[keyone]:
else:
continueconnect = 1
else:
if len(locationsgroup) > 0:
if locations[ii] not in locationsgroup[len(locationsgroup)]:
else:
continueconnect = 0
colortolocation[eachcolor] = locationsgroup

for kk in colortolocation[(0,0,0)]:
if len(colortolocation[(0,0,0)][kk]) > 7:
print kk
print colortolocation[(0,0,0)][kk]

On Wednesday, August 2, 2017 at 3:50:52 AM UTC+8, Ho Yeung Lee wrote:
> def isneighborlocation(lo1, lo2):
>     if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
>         return 1
>     elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
>         return 1
>     elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
>         return 1
>     else:
>         return 0
>
>
> sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))
>
> return something like
> [(1,2),(3,3),(2,5)]

```