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

Python - หาดัชนีเริ่มต้นของทุกลิสต์ซ้อน (Starting Index of All Nested Lists)


ตัวอย่าง

โค้ดด้านล่างคำนวณดัชนีเริ่มต้นของแต่ละ sublist หากนำมาต่อกันเป็นลิสต์แบน (flattened) โดยสะสมความยาว

my_list = [[51], [91, 22, 36, 44], [25, 25], [46, 67, 78, 82, 69, 29], [7, 5]]
print("The list is :")
print(my_list)
my_result = []
my_len = 0
for sub in my_list:
    my_result.append(my_len)
    my_len += len(sub)
print("The initial element indices are :")
print(my_result)

ผลลัพธ์

The list is : [[51], [91, 22, 36, 44], [25, 25], [46, 67, 78, 82, 69, 29], [7, 5]]
The initial element indices are : [0, 1, 5, 7, 13]

คำอธิบาย

  • กำหนดลิสต์ซ้อนและแสดงผล

  • สร้างลิสต์ว่าง my_result และตัวสะสม my_len = 0

  • วนลูปแต่ละ sublist: append my_len ปัจจุบัน เข้า result แล้วบวกความยาว sublist เข้า my_len

  • แสดงดัชนีเริ่มต้นของแต่ละ sublist