计算字典值(Python中的列表)中的项目数
我们得到了一个词典,其中键值对本身的值是一个列表。在本文中,我们将了解如何计算此列表中作为字典中的值显示的项目数。
与isinstance
印地语假设我们使用isinstance函数来查找字典的值是否为列表。然后,只要isinstance返回true,就增加一个count变量。
示例
# 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
用枚举
枚举功能还可以扩展并列出字典中的项目。我们应用实例来找出列出的值。
示例
# 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