Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo mẫu phần tử tăng dần xen kẽ trong list Python

Sử dụng List Comprehension với enumerate(). Python cung cấp cú pháp gọn gàng tạo list từ list khác (list comprehension). enumerate() thêm bộ đếm cho iterable.

Ví dụ

# Khai báo list số nguyên
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))

Kết quả

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