ที่นี่เรามีลิสต์จากผู้ใช้และขนาดการแบ่งที่กำหนด งานของเราคือแบ่งลิสต์ตามขนาดที่กำหนด
วิธีที่ 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)
def list_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
ใช้ List comprehension สามารถแก้ปัญหานี้ในบรรทัดเดียว
ตัวอย่างโค้ด
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]]