Project

General

Profile

« Previous | Next » 

Revision 1147

util.py: Added WrapIter to wrap an iterator and ListDict to view a list as a dict

View differences:

lib/util.py
49 49
        while func(iter_.curr()): iter_.next()
50 50
    except StopIteration: pass # nothing after the matching elements
51 51

  
52
def list_subset(list_, idxs):
53
    subset = []
54
    for idx in idxs:
55
        try: subset.append(list_[idx])
56
        except IndexError: pass
57
    return subset
52
class WrapIter:
53
    def __init__(self, wrap_func, iterable):
54
        self.wrap_func = wrap_func
55
        self.iter_ = iterable.__iter__()
56
    
57
    def __iter__(self): return self
58
    
59
    def next(self): return self.wrap_func(self.iter_.next())
58 60

  
59 61
class CheckedIter:
60 62
    def __init__(self, check_func, iterable):
......
74 76
    try: return list_[idx]
75 77
    except IndexError: return default
76 78

  
79
def list_subset(list_, idxs):
80
    subset = []
81
    for idx in idxs:
82
        try: subset.append(list_[idx])
83
        except IndexError: pass
84
    return subset
85

  
77 86
def list_eq_is(list0, list1):
78 87
    '''Compares two lists using is'''
79 88
    if len(list0) != len(list1): return False
......
101 110
def dict_subset_right_join(dict_, keys):
102 111
    '''Gets a subset of a dict, using None for subset keys that don't exist'''
103 112
    return dict_subset(DefaultDict(dict_), keys)
113

  
114
class ListDict:
115
    '''Views a list as a dict, given a key->index mapping'''
116
    def __init__(self, list_, keys, key_idxs=None):
117
        assert len(keys) == len(list_)
118
        if key_idxs == None: key_idxs = list_flip(keys)
119
        self.list = list_
120
        self.keys = keys
121
        self.key_idxs = key_idxs
122
    
123
    def __getitem__(self, key): return self.list[self.key_idxs[key]]
124
    
125
    def __str__(self): return str(dict(zip(self.keys, self.list)))

Also available in: Unified diff