เราได้รับพจนานุกรมซึ่งค่าจากคู่ค่าคีย์นั้นเป็นรายการ ในบทความนี้เราจะมาดูวิธีการนับจำนวนรายการในรายการนี้ที่แสดงเป็นค่าในพจนานุกรม
ด้วยตัวอย่าง
ภาษาฮินดี สมมติว่าเราใช้ฟังก์ชัน isinstance เพื่อค้นหาว่าค่าของพจนานุกรมเป็นรายการหรือไม่ จากนั้นเราเพิ่มตัวแปรการนับเมื่อใดก็ตามที่ isinstance คืนค่าเป็นจริง
ตัวอย่าง
# defining the dictionary
Adict = {'Days': ["Mon","Tue","wed","Thu"],
'time': "2 pm",
'Subjects':["Phy","Chem","Maths","Bio"]
}
print("Given dictionary:\n",Adict)
count = 0
# using isinstance
for x in Adict:
if isinstance(Adict[x], list):
count += len(Adict[x])
print("The number of elements in lists: \n",count) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given dictionary:
{'Days': ['Mon', 'Tue', 'wed', 'Thu'], 'time': '2 pm', 'Subjects': ['Phy', 'Chem', 'Maths', 'Bio']}
The number of elements in lists:
8 พร้อมไอเทม()
รายการใด () ที่เราวนซ้ำในแต่ละองค์ประกอบของพจนานุกรมและใช้ฟังก์ชัน isinstance เพื่อดูว่าเป็นรายการหรือไม่
ตัวอย่าง
# defining the dictionary
Adict = {'Days': ["Mon","Tue","wed","Thu"],
'time': "2 pm",
'Subjects':["Phy","Chem","Maths","Bio"]
}
print("Given dictionary:\n",Adict)
count = 0
# using .items()
for key, value in Adict.items():
if isinstance(value, list):
count += len(value)
print("The number of elements in lists: \n",count) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given dictionary:
{'Days': ['Mon', 'Tue', 'wed', 'Thu'], 'time': '2 pm', 'Subjects': ['Phy', 'Chem', 'Maths', 'Bio']}
The number of elements in lists:
8 พร้อมแจงนับ
ฟังก์ชันแจกแจงยังขยายและแสดงรายการของพจนานุกรม เราใช้เป็นตัวอย่างเพื่อค้นหาค่าที่เป็นรายการ
ตัวอย่าง
# defining the dictionary
Adict = {'Days': ["Mon","Tue","wed","Thu"],
'time': "2 pm",
'Subjects':["Phy","Chem","Maths","Bio"]
}
print("Given dictionary:\n",Adict)
count = 0
for x in enumerate(Adict.items()):
if isinstance(x[1][1], list):
count += len(x[1][1])
print(count)
print("The number of elements in lists: \n",count) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given dictionary:
{'Days': ['Mon', 'Tue', 'wed', 'Thu'], 'time': '2 pm', 'Subjects': ['Phy', 'Chem', 'Maths', 'Bio']}
8
The number of elements in lists:
8