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

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

方法1:使用yield

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

方法2:使用列表理解

列表理解是一种在一行代码中中断列表的优雅方法。

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

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: