-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathitertools_groupby_seq.py
More file actions
44 lines (34 loc) · 989 Bytes
/
Copy pathitertools_groupby_seq.py
File metadata and controls
44 lines (34 loc) · 989 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import functools
import operator
import pprint
from itertools import groupby, cycle, islice, count
@functools.total_ordering
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "({}, {})".format(self.x, self.y)
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __gt__(self, other):
return (self.x, self.y) > (other.x, other.y)
# Create a dataset of Point instances
data = list(map(Point, cycle(islice(count(), 3)), islice(count(), 7)))
print("Data: ")
pprint.pprint(data, width=35)
print()
# Try to group the unsorted data based on X values
print("Grouped, unsorted: ")
for k, g in groupby(data, operator.attrgetter("x")):
print(k, list(g))
print()
# Sort the data
data.sort()
print("Sorted: ")
pprint.pprint(data, width=35)
print()
# Group the sorted data based on X values
for k, g in groupby(data, operator.attrgetter("x")):
print(k, list(g))
print()