在4个项目的切片中分页python列表[重复]

时间:2021-02-22 21:39:17

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

可能重复:如何在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.

我需要将这些块传递给第三方API,它一次只能处理4个项目。我可以一次做一个,但它是每个go的HTTP请求和进程,所以我更愿意在尽可能少的查询中执行。

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 个解决方案

#1


31  

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]]

#1


31  

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]]