Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - ขยายลิสต์โดยทำซ้ำสมาชิก K ครั้ง

ทำซ้ำแต่ละสมาชิกในลิสต์ K ครั้ง

วิธีที่ 1: ใช้ Replication Operator

numbers = [1, 2, 3]
K = 5
result = []
for i in numbers:
    result += [i] * K
print(result)
# [1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3]

วิธีที่ 2: List Comprehension (Nested Loop)

numbers = [1, 2, 3]
K = 5
result = [i for i in numbers for _ in range(K)]
print(result)
# [1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3]

สรุป

ทั้งสองวิธีให้ผลเหมือนกัน List Comprehension กระชับกว่า