def test_itemfilter(self): D, kw = self.D, self.kw assert itemfilter(lambda item: iseven(item[0]), D({ 1: 2, 2: 3 }), **kw) == D({2: 3}) assert itemfilter(lambda item: iseven(item[1]), D({ 1: 2, 2: 3 }), **kw) == D({1: 2})
def valid_dict(d, keys=None): """ 检查是否字典中含有值为None的键(给定键的名称则检查给定的键,如果没有,则检查全部键) - 如果没有值为None的键,则返回True,反之False - 如果keys中的键不存在于d中,也返回False """ if keys is None: d_ = d else: d_ = itemfilter(lambda item: item[0] in keys, d) if len(d_) != len(keys): return False values = list(itervalues(d_)) return False if None in values else True
def test_itemfilter(self): D, kw = self.D, self.kw assert itemfilter(lambda item: iseven(item[0]), D({1: 2, 2: 3}), **kw) == D({2: 3}) assert itemfilter(lambda item: iseven(item[1]), D({1: 2, 2: 3}), **kw) == D({1: 2})
def filter(self, f: Callable[[Tuple[A, B]], bool]) -> 'Map[A, B]': return Map(dicttoolz.itemfilter(f, self))
def test_itemfilter(): assert itemfilter(lambda item: iseven(item[0]), {1: 2, 2: 3}) == {2: 3} assert itemfilter(lambda item: iseven(item[1]), {1: 2, 2: 3}) == {1: 2}
# #pip3 install itertoolz # # python3 demo.py # Now included since Python 3. #from itertoolz import filterfalse from itertools import filterfalse # See installation steps above. from toolz.dicttoolz import keyfilter, valfilter, itemfilter def is_even(x): if x % 2 == 0: return True else: return False def both_are_even(x): k, v = x if is_even(k) and is_even(v): return True else: return False print(list(filter(is_even, range(10)))) print(list(filterfalse(is_even, range(10)))) # Note: If we wrap these with a "list()" call then we don't print items, i.e. x:y print(keyfilter(is_even, {1: 2, 2: 3, 3: 4, 4: 5, 5: 6})) print(valfilter(is_even, {1: 2, 2: 3, 3: 4, 4: 5, 5: 6})) print(itemfilter(both_are_even, {1: 5, 2: 4, 3: 3, 4: 2, 5: 1}))