#统计字母频
import string
import random
import collections
y = collections.OrderedDict() #有序字典
y = collections.Counter() #更加快速的统计出现次数最多的元素
x = string.ascii_letters + string.digits
z = ''.join((random.choice(x) for i in range(1000)))
d = dict()
for ch in z:
d[ch] = d.get(ch,0) + 1
for k , v in sorted(d.items()):
print(k,":",v)
#pop() popitem() del clear() 用于删除
#Answer:
#0 : 18
#1 : 16
#2 : 13
#3 : 16
#4 : 17
#5 : 20
#6 : 18
#7 : 18
#8 : 20
#9 : 16
#A : 19
#B : 15
#C : 19
#D : 20
#E : 14
#F : 19
#G : 13
#H : 19
#I : 13
#J : 13
#K : 14
#L : 10
#M : 19
#N : 13
#O : 14
#P : 28
#Q : 23
#R : 11
#S : 16
#T : 11
#U : 15
#V : 24
#W : 24
#X : 16
#Y : 16
#Z : 16
#a : 18
#b : 16
#c : 17
#d : 12
#e : 16
#f : 11
#g : 15
#h : 14
#i : 21
#j : 16
#k : 20
#l : 16
#m : 18
#n : 22
#o : 10
#p : 12
#q : 17
#r : 9
#s : 13
#t : 14
#u : 13
#v : 15
#w : 15
#x : 17
#y : 12
#z : 15
# dictionary
# Python字典通过哈希表实现
x = dict()
x = {}
keys = ['a','b','c','d']
values = [1,2,3,4]
dictionary = dict (zip (keys , values))
print(dictionary)
#for i in range(1,4):
# print(dictionary[i])
#Answer:
#{'a': 1, 'b': 2, 'c': 3, 'd': 4}
#字典元素访问
if '10' in dictionary:
print(dictionary['10'])
else:
print("Not Exists!")
#Answer:
#Not Exists!
#防止被抛出异常,最好先使用类似于find的操作
#字典访问机制1
for key in dictionary:
print(key,dictionary[key],keys,values)
#Answer:values后加,可以使得最后一个元素后接空格
#a 1 ['a', 'b', 'c', 'd'] [1, 2, 3, 4]
#b 2 ['a', 'b', 'c', 'd'] [1, 2, 3, 4]
#c 3 ['a', 'b', 'c', 'd'] [1, 2, 3, 4]
#d 4 ['a', 'b', 'c', 'd'] [1, 2, 3, 4]
for i in dictionary:
print(i+str(dictionary[i]))
#Answer
#a1
#b2
#c3
#d4
#字典访问机制2
for k,v in dictionary.items():
print(k,v)
#Answer:items返回的是列表对象
#a 1
#b 2
#c 3
#d 4
for k,v in dictionary.items():
print(type(k),type(v))
#Answer:
#<class 'str'> <class 'int'>
#<class 'str'> <class 'int'>
#<class 'str'> <class 'int'>
#<class 'str'> <class 'int'>
#for k,v in dictionary.iteritems(): 该方法已被PY3删除!
# print(k,v)
Python 基本数据类型基础实战【字典(哈希表)】
最新推荐文章于 2023-07-30 18:52:11 发布