美文网首页我爱编程
python过滤工具

python过滤工具

作者: 有苦向瓜诉说 | 来源:发表于2018-06-22 00:05 被阅读27次

    过滤工具

    itertools.compress()以一个iterable对象和相应的Boolean选择器序列作为输入,然后输出iterable对象中对应选择器为True的元素,得到一个迭代器(可以使用list来转换为列表)。它能够十分方便的根据一个序列过滤另一个序列。

    from itertools import compress
    counts = [1, 2, 3, 4, 2, 8, 6, 4]
    data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
    selector = [n > 5 for n in counts]
    print(list(compress(data, selector)))
    
    

    自己怎么实现

    def compress(data,selector):
        return (d for d,s in zip(data,selector) if s)
    

    相关文章

      网友评论

        本文标题:python过滤工具

        本文链接:https://www.haomeiwen.com/subject/ppburftx.html