Created
April 3, 2015 16:53
-
-
Save mqingyn/cb0ef8de19c6270f63f9 to your computer and use it in GitHub Desktop.
sort_poi.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# Created by 'mengqingyun' on 15/4/3. | |
from collections import defaultdict, OrderedDict | |
import json | |
poi = [ | |
dict(typ='06', index=1.4, fl=1, rank=0.1), | |
dict(typ='05', index=1.2, fl=2, rank=1.5), | |
dict(typ='06', index=1.4, fl=4, rank=3.4), | |
dict(typ='04', index=1.3, fl=2, rank=2.3), | |
dict(typ='05', index=1.1, fl=3, rank=3.1), | |
dict(typ='06', index=1.4, fl=4, rank=1.1), | |
dict(typ='06', index=1.4, fl=4, rank=4.3), | |
dict(typ='05', index=1.5, fl=4, rank=2.6), | |
dict(typ='05', index=1.5, fl=4, rank=6.1), | |
dict(typ='02', index=1.0, fl=4, rank=0.1), | |
] | |
class Sort(object): | |
def sortit(self, pois, same_sort_cmp): | |
result = defaultdict(lambda: defaultdict(list)) | |
for poi in pois: | |
result[poi['fl']]['typ%s-%s' % (poi['typ'], poi['index'])].append(poi) | |
def _cmpdict(x, y): | |
indexx = x.split('-')[1] | |
indexy = y.split('-')[1] | |
if indexx < indexy: | |
return -1 | |
elif indexx > indexy: | |
return 1 | |
else: | |
return same_sort_cmp(x, y) | |
for k, v in result.iteritems(): | |
v = OrderedDict(sorted(v.items(), cmp=_cmpdict, key=lambda t: t[0], reverse=True)) | |
for ok, ov in v.iteritems(): | |
ov.sort(cmp=lambda x, y: cmp(x['rank'], y['rank']), reverse=True) | |
result[k] = v | |
return result | |
def sametyp_cmp(self, x, y): | |
return cmp(x, y) | |
def merge(self, top_size, sort_result): | |
""" | |
:param top_size: top_size | |
:param sort_result: | |
:return: | |
""" | |
poi_result = defaultdict(list) | |
for k, v in sort_result.iteritems(): | |
top = top_size if len(v) >= top_size else len(v) | |
typ_top = [v.popitem(last=False)[1] for i in range(top)] | |
# print typ_top | |
while reduce(lambda x, y: x + y, typ_top): | |
for poi_ in typ_top: | |
if poi_: | |
elm = poi_.pop(0) | |
poi_result[k].append(elm) | |
for val in v.values(): | |
poi_result[k] += val | |
return poi_result | |
sorter = Sort() | |
result = sorter.sortit(poi, sorter.sametyp_cmp) | |
# print result | |
print json.dumps(result[4], indent=1) | |
pois = sorter.merge(3, result) | |
print 'finish' | |
print json.dumps(pois[4], indent=1) | |
# print fl4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment