Python 字典的默认值
问题:
有时候我们需要建立一个映射表,因此我们需要一个字典结构。建立字典的时候,普通的字典结构需要key是否在字典内部,有一些其他的方法可以替代,如下:
代码:
1 from collections import defaultdict, Counter 2 3 4 def test_dict(): 5 arr = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] 6 mp1 = dict() 7 for i in arr: 8 if i in mp1: 9 mp1[i] += 1 10 else: 11 mp1[i] = 1 12 13 print("mp1=", mp1) 14 15 mp2 = dict() 16 for i in arr: 17 mp2[i] = mp2.get(i, 0) + 1 18 print("mp2=", mp2) 19 20 21 def test_defaultdict(): 22 arr = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] 23 mp3 = defaultdict(int) 24 for i in arr: 25 mp3[i] += 1 26 print("mp3=", mp3) 27 28 29 def test_Counter(): 30 arr = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] 31 mp4 = Counter() 32 for i in arr: 33 mp4[i] += 1 34 print("mp4=", mp4) 35 36 37 if __name__ == '__main__': 38 test_dict() 39 test_defaultdict() 40 test_Counter()
结果为:
mp1= {1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 1}
mp2= {1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 1}
mp3= defaultdict(<class 'int'>, {1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 1})
mp4= Counter({1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 1})
除了对数值类型,string也可以
1 from collections import defaultdict, Counter 2 3 4 def test_dict(): 5 mp1 = dict() 6 for i in arr: 7 if i in mp1: 8 mp1[i] += 1 9 else: 10 mp1[i] = 1 11 12 print("mp1=", mp1) 13 14 mp2 = dict() 15 for i in arr: 16 mp2[i] = mp2.get(i, 0) + 1 17 print("mp2=", mp2) 18 19 20 def test_defaultdict(): 21 mp3 = defaultdict(int) 22 for i in arr: 23 mp3[i] += 1 24 print("mp3=", mp3) 25 26 27 def test_Counter(): 28 mp4 = Counter() 29 for i in arr: 30 mp4[i] += 1 31 print("mp4=", mp4) 32 33 34 if __name__ == '__main__': 35 arr = ["hello", "world", "python", "is", "best", "language", "hello", "world"] 36 test_dict() 37 test_defaultdict() 38 test_Counter()
结果如下:
mp1= {'hello': 2, 'world': 2, 'python': 1, 'is': 1, 'best': 1, 'language': 1}
mp2= {'hello': 2, 'world': 2, 'python': 1, 'is': 1, 'best': 1, 'language': 1}
mp3= defaultdict(<class 'int'>, {'hello': 2, 'world': 2, 'python': 1, 'is': 1, 'best': 1, 'language': 1})
mp4= Counter({'hello': 2, 'world': 2, 'python': 1, 'is': 1, 'best': 1, 'language': 1})