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

Python – เพิ่มลิสต์ทุก N-th index


เมื่อต้องการเพิ่มลิสต์ทุก 'N' index ใช้การวนลูปง่ายและ 'enumerate'

ตัวอย่าง

สาธิตด้านล่าง:

my_list = [13, 27, 48, 12, 21, 45, 28, 19, 63] 
print("The list is :") 
print(my_list) 
append_list = ['P', 'Y', 'T'] 
N = 3 
print("The value of N is ") 
print(N) 
my_result = [] 
for index, element in enumerate(my_list): 
    if index % N == 0: 
        for element_in in append_list: 
            my_result.append(element_in) 
    my_result.append(element) 
print("The result is :") 
print(my_result)

ผลลัพธ์

The list is : [13, 27, 48, 12, 21, 45, 28, 19, 63] 
The value of N is 3 
The result is : ['P', 'Y', 'T', 13, 27, 48, 'P', 'Y', 'T', 12, 21, 45, 'P', 'Y', 'T', 28, 19, 63]

คำอธิบาย

  • กำหนดลิสต์และแสดงผล
  • กำหนดลิสต์ตัวอักษรที่จะเพิ่ม
  • กำหนดค่า N และแสดงผล
  • สร้างลิสต์ว่าง
  • วนลูปด้วย 'enumerate' ตรวจสอบ index % N == 0
  • ถ้าเป็น 0 ให้ append สมาชิกจาก append_list ทุกตัว
  • append element ปัจจุบันเข้าไป
  • แสดงผลลัพธ์บนคอนโซล