跳转到主要内容

包含用于操作可迭代对象的实用函数的库

项目描述

https://badge.fury.io/py/jk.png https://travis-ci.org/eliasdorneles/jk.png?branch=master https://pypip.in/d/jk/badge.png

包含用于操作可迭代对象的实用函数的库。

灵感来源于Python itertools的食谱和Ruby的Enumerable API。

适用于Python 2.6+和3.x。

特性

each_cons

  • each_cons(sequence, size)

懒惰地遍历一个序列,每次迭代返回给定大小的滑动窗口。

示例

计算季度销售报告

>>> import jk
>>> month_sales = [123.45, 54.3, 428.1, 144.2, 245.45, 197.3]
>>> for a, b, c in jk.each_cons(month_sales, 3):
...     print '%0.2f' % ((a + b + c)/3)
...
201.95
208.87
272.58
195.65

在文件中查找重复行

>>> lines = """here is a simple
... file for us to test.
... this line repeats
... this line repeats
... -- this one does not
... this one repeats too
... this one repeats too
... okay, we're done here""".split('\n')
>>>
>>> for ln, (a, b) in enumerate(jk.each_cons(lines, 2), 1):
...     if a == b:
...         print (ln, a)
...
(3, 'this line repeats')
(6, 'this one repeats too')

slice_before和slice_after

  • slice_before(predicate, sequence)

  • slice_after(predicate, sequence)

这些函数在处理具有某种类型分隔符的流时非常有用。例如,用于解析日志文件。

它们懒惰地遍历一个序列,返回一个元组,包含在谓词评估为True之前(或之后)切割的元素。

谓词参数也可以是一个字符串或正则表达式模式,用于匹配序列元素。

示例

分组数字直到为零

>>> numbers = [1, 2, 3, 0, 4, 5, 0, 6, 0, 7, 8]
>>> print list(jk.slice_after(lambda x: x == 0, numbers))
[(1, 2, 3, 0), (4, 5, 0), (6, 0), (7, 8)]

读取多行日志文件的条目

>>> log_lines = """START: initiating...
... kernel found
... EVENT: started
... moving on
... EVENT: something happened
... EVENT: another thing happened""".split('\n')
>>>
>>> for entry in jk.slice_before('^(START|EVENT):', log_lines):
...     print entry
...
('START: initiating...', 'kernel found')
('EVENT: started', 'moving on')
('EVENT: something happened',)
('EVENT: another thing happened',)

first, second和nth

  • first(sequence, default=None)

返回序列的第一个元素(如果序列为空,则返回默认值)。

  • second(sequence, default=None)

返回序列的第二个元素(如果不存在,则返回默认值)。

  • nth(sequence,n,default=None)

返回序列的第n个元素(如果不存在,则返回默认值)。

注意,参数n不是基于0的索引:它是一个序数,因此n=1表示第一个元素,n=4表示第四个元素,依此类推。

历史

0.1.0 (2014-11-23)

  • 首次发布在PyPI上。

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源代码分发

jk-0.1.0.tar.gz (14.3 kB 查看散列值)

上传时间 源代码

由以下支持