# 在Python中如何将列表分成大小为N的块？

2021年3月24日14:22:50 发表评论 848 次浏览

yield关键字使函数可以重新调用时再次中断的地方。这是与常规功能的关键区别。常规功能无法从中断处返回。 yield关键字可帮助函数记住其状态。通过yield可以使函数挂起并恢复, 同时在执行暂停时上交一个值。

``````my_list = [ 'geeks' , 'for' , 'geeks' , 'like' , 'geeky' , 'nerdy' , 'geek' , 'love' , 'questions' , 'words' , 'life' ]

# Yield successive n-sized
# chunks from l.
def divide_chunks(l, n):

# looping till length l
for i in range ( 0 , len (l), n):
yield l[i:i + n]

# How many elements each
# list should have
n = 5

x = list (divide_chunks(my_list, n))
print (x)``````

``[['geeks', 'for', 'geeks', 'like', 'geeky'], ['nerdy', 'geek', 'love', 'questions', 'words'], ['life']]``

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

# How many elements each
# list should have
n = 4

# using list comprehension
final = [my_list[i * n:(i + 1 ) * n] for i in range (( len (my_list) + n - 1 ) / / n )]
print (final)``````

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

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

# How many elements each
# list should have
n = 4

# using list comprehension
x = [l[i:i + n] for i in range ( 0 , len (l), n)]
print (x)``````

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