您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在可迭代的事物中计算匹配元素的大多数pythonic方法

在可迭代的事物中计算匹配元素的大多数pythonic方法

不得不反复遍历列表并不是很好的恕我直言。

我可能会创建一个允许执行以下操作的函数

twos, threes = countmatching(xrange(1,10),
                             lambda a: a % 2 == 0,
                             lambda a: a % 3 == 0)

起点将是这样的:

def countmatching(iterable, *predicates):
    v = [0] * len(predicates)
    for e in iterable:
        for i,p in enumerate(predicates):
            if p(e):
                v[i] += 1
    return tuple(v)

顺便说一句,“ itertools食谱”有一个类似alt4的食谱。

def quantify(seq, pred=None):
    "Count how many times the predicate is true in the sequence"
    return sum(imap(pred, seq))
python 2022/1/1 18:46:15 有464人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶