在本文中,我们将介绍如何在Python中将列表拆分为大小均匀的块。
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']]
在这个例子中,我们使用了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]
在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]]
在这里,我们使用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])]
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)]
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为空时,循环中断,这表明所有元素都已被处理。
这里有一个例子,你可以轻松地处理大小为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]