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

Python – Index Value Repetition ใน List (ทำซ้ำ Index ตามค่า)

ภาพรวม

สร้าง list ใหม่โดยทำซ้ำ index ตามค่าที่อยู่ใน list เดิม เช่น index 0 มีค่า 4 -> ทำซ้ำ 0 จำนวน 4 ครั้ง

ตัวอย่างโค้ด

my_list = [4, 0, 3, 1]
print("The list is:", my_list)

my_result = [index for index, value in enumerate(my_list) for _ in range(value)]
print("The result is:", my_result)

ผลลัพธ์

The list is: [4, 0, 3, 1]
The result is: [0, 0, 0, 0, 2, 2, 2, 3]

คำอธิบาย

  • index 0, value 4 -> เพิ่ม 0 จำนวน 4 ครั้ง
  • index 1, value 0 -> เพิ่ม 1 จำนวน 0 ครั้ง (ข้าม)
  • index 2, value 3 -> เพิ่ม 2 จำนวน 3 ครั้ง
  • index 3, value 1 -> เพิ่ม 3 จำนวน 1 ครั้ง

วิธีเข้าใจ List Comprehension นี้

# เทียบเท่ากับ:
result = []
for index, value in enumerate(my_list):
    for _ in range(value):
        result.append(index)

ประยุกต์ใช้

  • ขยายข้อมูลตาม weight (weighted sampling)
  • สร้าง index array สำหรับ repeat operations
  • ใช้กับ numpy: np.repeat(np.arange(len(arr)), arr)