Bil*_*ull 4 python python-2.4 python-2.5 python-itertools
您好我正在使用python的itertools中的Grouper函数来切割大块的select,其中(idlist)查询sqlite性能.问题是在chunksize的整个空间填充石斑鱼,即使列表要小得多,所以我不得不添加一个循环和比较,之前我想优化.
# input list shorter than grouper chunk size
input = (1,2,3,4,5)
grouper(10,input)
# desired output = (1,2,3,4,5)
# actual output = (1,2,3,4,5,None,None,None,None,None)
# current fix for this issue
list_chunks = tuple(tuple(n for n in t if n) for t in grouper(10, input))
Run Code Online (Sandbox Code Playgroud)
我认为必须有一种方法可以做到这一点,没有这个循环和比较.
如果不是过滤掉None条目,而是重写grouper()以返回您想要的选项,您可以使用以下解决方案itertools.islice:
def grouper(n, iterable):
it = iter(iterable)
x = tuple(islice(it, n))
while x:
yield x
x = tuple(islice(it, n))
Run Code Online (Sandbox Code Playgroud)
或更短的等价物(稍微难以理解):
def grouper(n, iterable):
it = iter(iterable)
return iter(lambda: tuple(islice(it, n)), ())
Run Code Online (Sandbox Code Playgroud)
例:
>>> list(grouper(5, range(12)))
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9), (10, 11)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
515 次 |
| 最近记录: |