在Python中将列表分成大小为N的块
在这里,我们将具有给定的用户输入列表和给定的中断大小。我们的任务是按照给定的大小打破列表。
方法1
在这里,我们使用yield关键字,它启用了一个功能,该功能先退出,然后再次调用,这是与常规函数的主要区别。
范例程式码
A=list()
n=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n)):
p=int(input("Size="))
A.append(int(p))
print (A)
deflist_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
n=int(input("Enter Chunk Size"))
my_list = list(list_chunks(A, n))
print ("List of Chunks",my_list)输出结果
Enter the size of the List 6 Enter the number Size= 12 [12] Size= 33 [12, 33] Size= 11 [12, 33, 11] Size= 56 [12, 33, 11, 56] Size= 44 [12, 33, 11, 56, 44] Size= 89 [12, 33, 11, 56, 44, 89] Enter Chunk Size 3 List of Chunks [[12, 33, 11], [56, 44, 89]]
方法2
使用列表理解,我们可以在一行中解决此问题。
范例程式码
A=list()
n=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n)):
p=int(input("Size="))
A.append(int(p))
print (A)
n=int(input("Enter Chunk Size"))
my_final = [A[i * n:(i + 1) * n] for i in range((len(A) + n - 1) // n )]
print ("List of chunks:",my_final)输出结果
Enter the size of the List 6 Enter the number Size= 23 [23] Size= 34 [23, 34] Size= 12 [23, 34, 12] Size= 56 [23, 34, 12, 56] Size= 33 [23, 34, 12, 56, 33] Size= 22 [23, 34, 12, 56, 33, 22] Enter Chunk Size 3 List of chunks: [[23, 34, 12], [56, 33, 22]]
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿