Paging python lists in slices of 4 items [duplicate]

耗尽温柔 提交于 2019-11-29 11:53:01

问题


Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]

I need to pass blocks of these to a third party API that can only deal with 4 items at a time. I could do one at a time but it's a HTTP request and process for each go so I'd prefer to do it in the lowest possible number of queries.

What I'd like to do is chunk the list into blocks of four and submit each sub-block.

So from the above list, I'd expect:

[[1, 2, 3, 4], [5, 6, 7, 8], [9]]

回答1:


mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] 
print [mylist[i:i+4] for i in range(0, len(mylist), 4)]
# Prints [[1, 2, 3, 4], [5, 6, 7, 8], [9]]


来源:https://stackoverflow.com/questions/3950079/paging-python-lists-in-slices-of-4-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!