python - Complex grouping list items -
i need display notifications in facebook format using python. finding difficult group items. following list query
the notification must displayed follows
- john changed name, code, description of product shirt
- john changed name of product hat
- john changed variant code of hat
- mike changed name of product trouser, hat
- kiet changed name of variant xxl shirt
is there possibility of doing using python group by? , order date?
you try following approach using groupby
, seems work existing data might need further thought other edge cases:
from itertools import groupby datetime import datetime results = [ ["user", "type", "changed", "product name", "date"], ["john", "product", "name", "shirt", "1-jan-17"], ["john", "product", "code", "shirt", "1-jan-17"], ["john", "product", "description", "shirt", "1-jan-17"], ["john", "product", "name", "hat", "1-jan-17"], ["john", "variant", "code", "xxl shirt", "1-jan-17"], ["mike", "product", "name", "trouser", "2-jan-17"], ["mike", "product", "name", "tie", "3-jan-17"], ["kiet", "variant", "name", "xxl shirt", "4-jan-17"]] sorted_results = sorted(results[1:], key=lambda x: (datetime.strptime(x[4], '%d-%b-%y'), x[0])) k1, g1 in groupby(sorted_results, lambda x: x[0]): grouped_by_name = list(g1) v1, v2 = [], [] k2, g2 in groupby(grouped_by_name, lambda x: (x[1], x[3])): # type, name v1.append(list(g2)) k2, g2 in groupby(grouped_by_name, lambda x: (x[1], x[2])): # type, changed v2.append(list(g2)) if len(v1) < len(v2): entry in v1: entries = [changed user, ptype, changed, pname, date in entry] print("{} changed {} of {} {}".format(entry[0][0], ', '.join(entries), entry[0][1], entry[0][3])) else: entry in v2: entries = [pname user, ptype, changed, pname, date in entry] print("{} changed {} of {} {}".format(entry[0][0], entry[0][2], entry[0][1], ', '.join(entries)))
this display following output:
john changed name, code, description of product shirt john changed name of product hat john changed code of variant xxl shirt mike changed name of product trouser, tie kiet changed name of variant xxl shirt
Comments
Post a Comment