how to group by function if one of the group has relationship with another one in the group?

Ho Yeung Lee jobmattcon at gmail.com
Mon Jul 24 23:53:51 EDT 2017


from itertools import groupby

testing1 = [(1,1),(2,3),(2,4),(3,5),(3,6),(4,6)]
def isneighborlocation(lo1, lo2):
    if abs(lo1[0] - lo2[0]) == 1  or lo1[1] == lo2[1]:
        return 1
    elif abs(lo1[1] - lo2[1]) == 1  or lo1[0] == lo2[0]:
        return 1
    else:
        return 0

groupda = groupby(testing1, isneighborlocation)
for key, group1 in groupda:
    print key
    for thing in group1:
        print thing

expect output 3 group
group1 [(1,1)]
group2 [(2,3),(2,4]
group3 [(3,5),(3,6),(4,6)]



More information about the Python-list mailing list