Python中将列表拆分为大小为N的块

在本文中,我们将介绍如何在Python中将列表拆分为大小均匀的块。

方法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:使用for循环

在这个例子中,我们使用了Python中的循环和列表切片,这将帮助我们将列表分成块。

my_list = [1, 2, 3, 4, 5,
           6, 7, 8, 9]
start = 0
end = len(my_list)
step = 3
for i in range(start, end, step):
    x = i
    print(my_list[x:x+step])

输出

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

方法3: 使用列表解析

在Python中,将列表拆分为一行代码,将列表拆分为多个列表是一种优雅的方式。

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

方法4:使用Numpy

在这里,我们使用Numpy.array_split,它将数组拆分为n个大小相等的块。

import numpy as np
  
arr = range(30)
np.array_split(arr, 6)

输出

[array([0, 1, 2, 3, 4]),
 array([5, 6, 7, 8, 9]),
 array([10, 11, 12, 13, 14]),
 array([15, 16, 17, 18, 19]),
 array([20, 21, 22, 23, 24]),
 array([25, 26, 27, 28, 29])]

方法5:使用itertools

from itertools import islice
  
  
def chunk(arr_range, arr_size):
    arr_range = iter(arr_range)
    return iter(lambda: tuple(islice(arr_range, arr_size)), ())
  
  
print(list(chunk(range(30), 5)))

输出

[(0, 1, 2, 3, 4),
 (5, 6, 7, 8, 9),
 (10, 11, 12, 13, 14),
 (15, 16, 17, 18, 19),
 (20, 21, 22, 23, 24),
 (25, 26, 27, 28, 29)]

方法6: 使用collections

from collections import deque
  
def split_list(input_list, chunk_size):
  # Create a deque object from the input list
  deque_obj = deque(input_list)
  # While the deque object is not empty
  while deque_obj:
      # Pop chunk_size elements from the left side of the deque object
      # and append them to the chunk list
      chunk = []
      for _ in range(chunk_size):
        if deque_obj:
          chunk.append(deque_obj.popleft())
          
      # Yield the chunk
      yield chunk
input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunk_size = 3
chunks = list(split_list(input_list, chunk_size))
print(chunks) 

输出

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

deque类允许您轻松地从列表的左侧或右侧移除元素,从而轻松地将列表分割为特定大小的块。代码使用while循环和生成器函数迭代列表,每次生成一个块。当deque为空时,循环中断,这表明所有元素都已被处理。

方法7: 部分赋值

这里有一个例子,你可以轻松地处理大小为N的块列表:

my_list = list(range(10))
chunk_size = 3
while my_list:
    chunk, my_list = my_list[:chunk_size], my_list[chunk_size:]
    print(chunk)

输出

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值