建设网站时间推进表,广西建设职业技术学院网站,ui设计是什么职业,东莞专业做网站优化在本文中#xff0c;我们将介绍如何在Python中将列表拆分为大小均匀的块。
方法1#xff1a;使用yield
yield关键字使函数能够在再次调用时返回到它停止的位置。这是与常规函数的关键区别#xff0c;一个常规的函数不能回到它停止的地方。yield关键字帮助函数记住其状态我们将介绍如何在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 lfor i in range(0, len(l), n): yield l[i:i n]# How many elements each
# list should have
n 5x 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 iprint(my_list[x:xstep])输出
[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 nparr 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 islicedef 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 dequedef split_list(input_list, chunk_size):# Create a deque object from the input listdeque_obj deque(input_list)# While the deque object is not emptywhile deque_obj:# Pop chunk_size elements from the left side of the deque object# and append them to the chunk listchunk []for _ in range(chunk_size):if deque_obj:chunk.append(deque_obj.popleft())# Yield the chunkyield 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]