1. 为元组命名,提高可读性
# 定义元组名称
_NAME, _AGE, _SEX, _EMAIL = range(4)
def way1():
student = ('Jim', 16, 'male', 'a@gmail.com')
print(student[_NAME])
print(student[_AGE])
print(student[_SEX])
print(student[_EMAIL])
def way2():
from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
s = Student('Jim', 16, 'male', 'a@gmail.com')
print(s)
print(s.name)
if __name__ == '__main__':
way2()
2. 统计元组中出现的频度
def count_nums1():
'''
# 创建字典,data中数据作为key, value为0
# 迭代data,相同值value+1
:return:
'''
data = [randint(0, 10) for _ in range(30)]
data_dict = dict.fromkeys(data, 0)
for i in data:
data_dict[i] += 1
print(data_dict)
def count_nums2():
'''
# 使用Counter包,most_common(n)
前n个高频词
:return:
'''
from collections import Counter
data = [randint(0, 10) for _ in range(30)]
data_dict = Counter(data)
print(data_dict.most_common(3))
网友评论