[英]Get remainder of a list
我有一個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)個元素之后我將丟失列表的其余部分。
如何獲得列表的其余部分並將其插入?
如果package不為空,只需在循環結束時調用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)
如果不介意使用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.