Python|计算作为列表的字典值中的项目数
在Python中,字典是一个无序、可变和索引的集合。字典是用大括号写的,它们有键和值。它用于散列特定的密钥。
字典有多个key:value
对。可以有多个对,其中一个键对应的值是一个列表。要检查该值是否为列表,我们使用Python中内置的isinstance()
方法。
isinstance()
方法有两个参数:
object - object to be checked
classinfo - class, type, or tuple of classes and types
它返回一个布尔值,无论对象是否是给定类的实例。
让我们讨论不同的方法来计算作为列表的字典值中的项目数。
方法 #1使用in
运算符
# Python program to count number of items
# in a dictionary value that is a list.
def main():
# defining the dictionary
d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# using the in operator
count = 0
for x in d:
if isinstance(d[x], list):
count += len(d[x])
print(count)
# Calling Main
if __name__ == '__main__':
main()
输出:
14
方法 #2:使用列表推导
# Python program to count number of items
# in a dictionary value that is a list.
def main():
# defining the dictionary
d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# using list comprehension
print(sum([len(d[x]) for x in d if isinstance(d[x], list)]))
if __name__ == '__main__':
main()
输出:
14
方法#3:使用dict.items()
# Python program to count number of items
# in a dictionary value that is a list.
def main():
# defining the dictionary
d = { 'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# using dict.items()
count = 0
for key, value in d.items():
if isinstance(value, list):
count += len(value)
print(count)
if __name__ == '__main__':
main()
输出:
14
方法 #4:使用enumerate()
# Python program to count number of items
# in a dictionary value that is a list.
def main():
# defining the dictionary
d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# using enumerate()
count = 0
for x in enumerate(d.items()):
# enumerate function returns a tuple in the form
# (index, (key, value)) it is a nested tuple
# for accessing the value we do indexing x[1][1]
if isinstance(x[1][1], list):
count += len(x[1][1])
print(count)
if __name__ == '__main__':
main()
输出:
14