输入数字or 字符串,统计重复次数---字典统计练习
1 ''' 2 输入一个数字,打印每一位及其重复次数 3 ''' 4 num = input("input a num:").strip().lstrip('0') # '00100' 5 6 # NO 1 7 counter = {} 8 for i in num: 9 counter[i] = counter.get(i, 0) + 1 10 print(counter) 11 # NO 2 12 counter = {} 13 for i in num: 14 if i not in counter: 15 counter[i] = 0 16 counter[i] += 1 17 print(counter) 18 19 # NO 3 20 counter = {} 21 for i in num: 22 counter[i] = counter.setdefault(i, 0) + 1 23 print(counter) 24 25 # NO 4 26 counter = dict.fromkeys(range(10),0) 27 for i in num: 28 counter[int(i)] += 1 29 print(counter) 30 31 ''' 32 {'1': 1, '2': 1, '3': 2, '4': 2, '5': 2} 33 {'1': 1, '2': 1, '3': 2, '4': 2, '5': 2} 34 {'1': 1, '2': 1, '3': 2, '4': 2, '5': 2} 35 {0: 0, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 0, 7: 0, 8: 0, 9: 0} 36 '''
1 ''' 2 数字重复统计: 3 随机产生100个整数 4 数字的范围 【-1000,1000】 5 升序输出及重复次数 6 ''' 7 8 # NO 1 9 import random 10 from collections import defaultdict 11 12 nums = [random.randint(-1000,1000) for _ in range(100)] 13 counter = defaultdict(int) 14 15 for i in nums: 16 counter[i] += 1 17 #使用内建方法sorted() 排序),会生成一个新的list 18 print(sorted(counter.items(),reverse=True)) # items() 是按照key 排序的,如果value排序,需要高阶函数配合 19 20 # NO 2 21 # 使用了 list 的sort() 等效于内建方法sorted() 22 # 通过测试,事实上,这个效率比内建函数要高 23 import random 24 nums = [random.randint(-1000,1000) for _ in range(100)] 25 26 counter = defaultdict(int) 27 28 for i in nums: 29 counter[i] += 1 30 keys = list(counter.keys()) # 取出keys 31 keys.sort() # 就地排序 32 newlist = [0] * len(keys) 33 for i,v in enumerate(keys): 34 newlist[i] = v, counter[v] 35 print(newlist)
1 ''' 2 字符串重复统计 3 'abcdefghijklmnopqrstuvwxyz' 4 随机挑选两个字母,共挑选100个 5 降序输出所有不同的字符串,重复次数 6 ''' 7 8 import string 9 import random 10 11 # 取26个字母; 12 a = string.ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz' 13 # # s = '' 14 # # for i in range(97,123): 15 # # s += chr(i) # 'abcdefghijklmnopqrstuvwxyz' 16 # 取100个 17 words = [random.choice(a) +random.choice(a) for _ in range(100)] 18 19 counter = {} 20 for word in words: 21 counter[word] = counter.get(word, 0) + 1 22 23 # print(counter) 24 print(sorted(counter.items(), reverse=True)) 25 26 27 # dic = dict({1:2,2:2,5:1,3:9}) 28 # dic[9] = 1 29 # dic[0] = 4 30 # print(dic) 31 # l = dic.items() 32 # print(l) # dict_items([(1, 2), (2, 2), (5, 1), (3, 9), (9, 1), (0, 4)]) 33 # print(sorted(l)) # [(0, 4), (1, 2), (2, 2), (3, 9), (5, 1), (9, 1)] 34 # print(l) # dict_items([(1, 2), (2, 2), (5, 1), (3, 9), (9, 1), (0, 4)])
为什么要坚持,想一想当初!