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

Python - สร้างดัชนี (Index Directory) ของสมาชิกในลิสต์


ตัวอย่าง

โค้ดด้านล่างสร้าง dictionary ที่ key คือค่าที่ไม่ซ้ำในลิสต์ และ value คือลิสต์ของดัชนีที่ค่านั้นปรากฏ โดยใช้ dictionary comprehension และ set

my_list = [81, 36, 42, 57, 68, 12, 26, 26, 38]
print("The list is :")
print(my_list)
my_result = {key: [index for index, value in enumerate(my_list) if value == key] for key in set(my_list)}
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : [81, 36, 42, 57, 68, 12, 26, 26, 38]
The result is : {36: [1], 68: [4], 38: [8], 42: [2], 12: [5], 81: [0], 57: [3], 26: [6, 7]}

คำอธิบาย

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

  • ใช้ dictionary comprehension: วน key ใน set(my_list) สร้างลิสต์ดัชนีโดย enumerate และกรอง value == key

  • แสดง dictionary ผลลัพธ์