# twoq / twoq / ordering.py

 ``` 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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94``` ```# -*- coding: utf-8 -*- '''twoq ordering mixins''' from threading import local from itertools import product, groupby from random import choice, shuffle, sample from twoq.support import zip_longest, imap class RandomMixin(local): '''random mixin''' def choice(self): '''random choice of/from incoming things''' with self._context(): return self._append(choice(list(self._iterable))) def sample(self, n): ''' random sampling drawn from `n` incoming things @param n: number of incoming things ''' with self._context(): return self._xtend(sample(list(self._iterable), n)) def shuffle(self): '''randomly order incoming things''' with self._context(): iterable = list(self._iterable) shuffle(iterable) return self._xtend(iterable) class OrderMixin(local): '''order mixin''' def group(self): ''' group incoming things, optionally using current call for key function ''' call_, list_ = self._call, list with self._context(): return self._xtend(imap( lambda x: [x[0], list_(x[1])], groupby(self._iterable, call_) )) def grouper(self, n, fill=None): ''' split incoming things into sequences of length `n`, using `fill` thing to pad incomplete sequences @param n: number of things @param fill: fill thing (default: None) ''' with self._context(): return self._xtend( zip_longest(fillvalue=fill, *[iter(self._iterable)] * n) ) def reverse(self): '''reverse order of incoming things''' with self._context(): return self._xtend(reversed(list(self._iterable))) def sort(self): ''' sort incoming things, optionally using current call as key function ''' call_ = self._call with self._context(): return self._xtend(sorted(self._iterable, key=call_)) class CombineMixin(local): '''combination mixin''' def product(self, n=1): ''' nested for each loops repeated `n` times @param n: number of repetitions (default: 1) ''' with self._context(): return self._xtend(product(*self._iterable, repeat=n)) class OrderingMixin(OrderMixin, RandomMixin, CombineMixin): '''ordering mixin''' ```