如何为元组中的每个元素命名,提高程序的可读性
from collections import namedtuple
# 通常需要采用下标访问元素
student = ("Jim", 18, "male", "tomtiddler@163.com")
# 1.采用常量定义
NAME, AGE, SEX, EMAIL = range(4)
# 2.采用nametuple
Student = namedtuple("Student", ["name", "age", "sex", "email"])
s = Student("Jim", 18, "male", "tomtiddler@163.com")
if __name__ == "__main__":
print(student[NAME], student[AGE])
print(s.name, s.age)
print(isinstance(s, tuple))
如何统计序列中元素出现的频度
- 某随机序列中,找出出现次数最高的三个元素,它们出现了多少次?
- 对某英文文章的单词,进行词频统计,找出出现次数最高的10个单词,它们出现了多少次?
import re
from random import randint
from collections import Counter
data = [randint(0, 20) for _ in range(100)]
c = dict.fromkeys(data, 0)
# c = dict.fromkeys(range(0, 21), 0) # 此处注意需要包括20
for x in data:
c[x] += 1
c2 = Counter(data)
txt = open("doc.txt", "r").read()
c3 = Counter(re.split("\W+", txt))
if __name__ == "__main__":
print(c)
print(c2)
print(c2.most_common(3))
print(c3)
print(c3.most_common(10))
字典
如何根据字典中值的大小,对字典中的项进行排序
某班英语成绩以字典的形式进行存储,根据成绩高低进行排名
from random import randint
student = {x: randint(50, 100) for x in "xyzabc"}
sor = sorted(zip(student.values(), student.keys()))
sor2 = sorted(student.items(), key=lambda x: x[1])
sor3 = sorted(student.items(), key=lambda x: x[1], reverse=True)
if __name__ == "__main__":
print(sor)
print(sor2)
# 降序排列
print(sor3)