File: itertools.py

package info (click to toggle)
pint-xarray 0.6.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,244 kB
  • sloc: python: 5,043; makefile: 4
file content (30 lines) | stat: -rw-r--r-- 782 bytes parent folder | download
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
import itertools
from functools import reduce


def separate(predicate, iterable):
    evaluated = ((predicate(el), el) for el in iterable)

    key = lambda x: x[0]
    grouped = itertools.groupby(sorted(evaluated, key=key), key=key)

    groups = {label: [el for _, el in group] for label, group in grouped}

    return groups[False], groups[True]


def unique(iterable):
    return list(dict.fromkeys(iterable))


def zip_mappings(*mappings):
    def common_keys(a, b):
        all_keys = unique(itertools.chain(a.keys(), b.keys()))
        intersection = set(a.keys()).intersection(b.keys())

        return [key for key in all_keys if key in intersection]

    keys = list(reduce(common_keys, mappings))

    for key in keys:
        yield key, tuple(m[key] for m in mappings)