获取列表的剩余部分

时间:2018-05-08 11:40:31

标签: python algorithm loops

我有一个python代码,它从表中获取所有行,并以1000块为单位将其插入到另一个中。

allRows = db.getAllRows() #12.345 elements
package = []
for idx, pr in enumerate(allRows):
    package.append(pr)
    if (idx + 1) % 1000 == 0:
        db.inserPackage(package)
        package = []

此代码可以工作并插入1000行的包,但是如果列表的长度是12.345,那么在12.000(345)元素之后我将丢失列表的其余部分。

我怎样才能获得列表的剩余部分并将其插入?

2 个答案:

答案 0 :(得分:3)

如果包不是空的话,只需在循环结束时调用db.insertPackage(package)

allRows = db.getAllRows() #12.345 elements
package = []
for idx, pr in enumerate(allRows):
    package.append(pr)
    if (idx + 1) % 1000 == 0:
        db.inserPackage(package)
        package = []
if package:
    db.inserPackage(package)

答案 1 :(得分:2)

如果不介意使用itertools,可以采用一种方便的方法:

import itertools

allRows = db.getAllRows() # 12.345 elements
while True:
    package = list(itertools.islice(allRows, 1000))
    if not package: # no more elements
        break
    db.insertPackage(package)