Python中統計字典值(列表)中專案的數量
我們有一個字典,其中鍵值對的值本身就是一個列表。在本文中,我們將瞭解如何計算字典值中作為列表存在的專案的數量。
使用isinstance
假設我們使用isinstance函式來確定字典的值是否為列表。然後,每當isinstance返回true時,我們都會遞增一個計數變數。
示例
# 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使用items()
使用items(),我們遍歷字典的每個元素,並應用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使用enumerate
enumerate函式也展開並列出字典的專案。我們應用is instance來找出哪些值為列表。
示例
# 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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP