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

更新于:2020年6月4日

980 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告