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

วิธีสร้าง Python Dictionary ด้วย Enumerate Function

ฟังก์ชัน enumerate() ของ Python รับ Iterable อะไรก็ได้เป็น Argument และคืนค่า Enumerate Object ซึ่งสามารถใช้ Traverse Iterable ได้ มี Index และ Item ที่ตรงกันใน Iterable Object เช่น List, Tuple หรือ String

Enumerate Object ที่มี Index และ Value นี้จะถูกแปลงเป็น Dictionary โดยใช้ Dictionary Comprehension

>>> l1 = ['aa', 'bb', 'cc', 'dd']
>>> enum = enumerate(l1)
>>> enum
>>> d = dict((i, j) for i, j in enum)
>>> d
{0: 'aa', 1: 'bb', 2: 'cc', 3: 'dd'}