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

Python - รูปแบบการเพิ่มสมาชิกสลับกันในลิสต์

ใช้ list comprehension ร่วมกับ enumerate() สร้างรูปแบบสมาชิกสลับกัน

ตัวอย่าง

my_list = [1, 2, 3]
print("Printing my_list list : " + str(my_list))
response = [value for sub in ((i, "*" * j) for j, i in enumerate(my_list, 1)) for value in sub]
print("The increasing element pattern IS : " + str(response))

ผลลัพธ์

Printing my_list list : [1, 2, 3]
The increasing element pattern IS : [1, '*', 2, '**', 3, '***']