在领扣的刷题过程中,经常需要使用到python中字典进行映射或者计数(类似于Java和C++中的map的功能),并且有的时候需要对字典进行遍历进行进一步的操作,下面是常见的字典的遍历方法:
import collections
if __name__ == '__main__':
dic = [1, 1, 2, 4, 3, 10, 3, 2]
# 使用collections.Counter方法将列表转为字典的形式并且对其计数
dic = collections.Counter(dic)
# print(dic)
# 遍历字典
for cur in dic.items():
print(cur[0], cur[1], end="\n")
import collections
if __name__ == '__main__':
dic = [1, 1, 2, 4, 3, 10, 3, 2]
# 使用collections.Counter方法将列表转为字典的形式并且对其计数
dic = collections.Counter(dic)
# print(dic)
# 遍历字典
for key, value in dic.items():
print(key, value, end="\n")
import collections
if __name__ == '__main__':
dic = [1, 1, 2, 4, 3, 10, 3, 2]
dic = collections.Counter(dic)
# 遍历字典的键
for key in dic.keys():
print(key, end="\n")
# 遍历字典的值
for value in dic.values():
print(value, end="\n")