File size: 1,266 Bytes
d6d3a5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import math


def chunks_by_len(L, n):
    """
    Split a list into n chunks
    """
    num_chunks = int(math.ceil(float(len(L)) / n))
    splits = [L[x : x + num_chunks] for x in range(0, len(L), num_chunks)]
    return splits


def chunks_by_size(L, n):
    """Yield successive n-sized chunks from lst."""
    seqs = []
    for i in range(0, len(L), n):
        seqs.append(L[i : i + n])
    return seqs


def unsort(L, sort_idx):
    assert isinstance(sort_idx, list)
    assert isinstance(L, list)
    LL = zip(sort_idx, L)
    LL = sorted(LL, key=lambda x: x[0])
    _, L = zip(*LL)
    return list(L)


def add_prefix_postfix(mydict, prefix="", postfix=""):
    assert isinstance(mydict, dict)
    return dict((prefix + key + postfix, value) for (key, value) in mydict.items())


def ld2dl(LD):
    assert isinstance(LD, list)
    assert isinstance(LD[0], dict)
    """
    A list of dict (same keys) to a dict of lists
    """
    dict_list = {k: [dic[k] for dic in LD] for k in LD[0]}
    return dict_list


def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    seqs = []
    for i in range(0, len(lst), n):
        seqs.append(lst[i : i + n])
    seqs_chunked = sum(seqs, [])
    assert set(seqs_chunked) == set(lst)
    return seqs