Python-字典和集合编程技巧

hello,这里是Token_w的博客,欢迎您的到来
今天主要讲解Python字典和集合在实际编程中的使用技巧
整理不易,对您有所帮助,希望得到你的支持!感谢!!!

1.如何在列表、字典、集合中根据条件筛选数据?

实际案例

  • 案例1:过滤掉列表[3, 9, -1, 10, 20, -2, …] 中的负数
  • 案例2:筛出字典{‘lisi’: 79, ‘Jin’: 88, ‘lucy’: 93, … }中值高于90的项
  • 案例3:筛出集合{77, 89, 34, 20, 21…}中能被3整除的元素
    这类问题比较简单,通常的做法就是依次迭代列表、字典、集合中的每个项,进行条件判断。

但是在python中,还有更高级的方法来解决这类问题,并且更简单高效。

01 案例1:过滤掉列表[3, 9, -1, 10, 20, -2, …] 中的负数

方法一:使用 filter 函数

from random import randint

# 使用列表解析生成 -10~10 之间的10个元素
data = [randint(-10, 10) for _ in range(10)]

print('原始列表为:' , data)

# filter(function or None, iterable) --> filter object
data_o = filter(lambda x: x >= 0, data)

for each in data_o:
    
    print(each)

方法二:使用列表解析

from random import randint

# 使用列表解析生成 -10~10 之间的10个元素
data = [randint(-10, 10) for _ in range(10)]

print('原始列表为:',  data)

data_o = [x for x in data if x >= 0]

print(data_o)

02 案例2:筛出字典{‘lisi’: 79, ‘Jin’: 88, ‘lucy’: 93, … }中值高于90的项

from random import randint

# 使用字典解析生成 一个字典
d ={
    
    x: randint(60, 100) for x in range(1, 10)}
print(d)

d_o = {
    
    k: v for k, v in d.items() if v >= 90}

print(d_o)

03 案例3:筛出集合{77, 89, 34, 20, 21…}中能被3整除的元素

from random import randint

# 使用集合解析生成 -10~10 之间的10个元素
data = {
    
    randint(-10, 10) for _ in range(10)}

print('原始集合为:', data)

data_o = {
    
    x for x in data if x % 3 == 0}

print(data_o)

2.如何为元组中的每个元素命名,提高程序可读性?

stuents = ('Jim', 16, 'male', '[email protected]')
name=stuents[0]
age=stuents[1]
sex= stuents[2]
email=stuents[3]
print(name, age, sex, email)

01 方法一:定义类似与其他语言的枚举类型,也就是定义一系列数值常量

s=stuents = ('Jim', 16, 'male', '[email protected]')
NAME, AGE, SEX, EMAIL = range(4)
name=s[NAME]
age=s[AGE]
sex= s[SEX]
email=s[EMAIL]
print(name, age, sex, email)

02 方法二:使用标准库中 collections.nameedtuple 替代内置 tuple

from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
s = Student('Jim', 16, 'male', '[email protected]')
print(s)
# Student(name='Jim', age=16, sex='male', email='[email protected]')

print(s.name)
# 'Jim'

print(s.age)
# 16

print(s.sex)
# 'male'

print(s.email)
# '[email protected]'

3.如何统计序列中元素的出现频度?

案例1:

方法一:传统方法

from random import randint

# 随机生成一个列表
data = [randint(0, 20) for _ in range(30)]

# 以列表中的值为字典的键,0为字典的值建立字典
c = dict.fromkeys(data, 0)

# 依次遍历列表,遇到一个元素,就把字典中对应的键的值加1
for x in data:

    c[x] += 1

print(c)

方法二:使用 collections.Counter 对象

将序列传入 Counter 的构造器,得到 Counter 对象是元素频率的字典
Counter.most_common(n) 方法得到频率最高的 n 个元素的列表

from random import randint
from collections import Counter

# 随机生成一个列表
data = [randint(0, 20) for _ in range(30)]

c = Counter(data)

# 得到的 c 就是一个collections.Counter类型的数据,和方法 一 结果一样
# 用法与字典一样,例如 c[2] , 就是得到 键为2 对应的值
print(c)

# 另外,还可以使用 most_common() 方法得到 出现频率最高的几个键和值
print(c.most_common(3))  # 输出前3名

案例2:

from collections import Counter
import re

with open('./test.txt', 'r') as f:
    txt = f.read()

# 使用 正则表达式 对文本进行切割,按照 非字母字符 进行切割
l1 = re.split('\W+', txt)

c = Counter(l1)

# 得到频率最高的10个单词
print(c.most_common(10))

4.如何根据字典中值的大小,对字典中的项排序?

01 方法一:使用zip将字典数据转换为元组

from random import randint

# 生成随机字典
d = {
    
    x:randint(60,100) for x in 'xyzabc'}

print(d)

# 把值放在前面,键放在后面,构成元组,每个元组为列表的一个项
# 得到的结果为 [(74, 'z'), (80, 'y')...]形式
list1 = zip(d.values(), d.keys())

# 然后对得到的列表进行排序,就会以列表中的元组的第一项排序,相同时再比较第二项

print(sorted(list1))

02 方法二:使用 sorted 函数的 key 参数

from random import randint

# 生成随机字典
d = {
    
    x:randint(60,100) for x in 'xyzabc'}

print(d)

# d.items() 也是一个元组的列表,只是元组中键在前,值在后
# 使用 key 参数设置以第二项 (值)作为排序依据

print(sorted(d.items(), key = lambda x: x[1]))

5.如何快速找到多个字典中的公共键?

01 方法一:传统方法,依次遍历

from random import randint, sample

# 随机产生 3 场球赛的 进球人和数
s1 = {
    
    x: randint(1,4) for x in sample('abcdefg',randint(3,6))}
s2 = {
    
    x: randint(1,4) for x in sample('abcdefg',randint(3,6))}
s3 = {
    
    x: randint(1,4) for x in sample('abcdefg',randint(3,6))}

print(s1)
print(s2)
print(s3)


# 传统方法
res = []

for k in s1:
    if k in s2 and k in s3:
        res.append(k)
       
print(res)

02 方法二:利用集合(set)的交集操作

利用字典的keys() 方法,得到一个字典的 keys 的集合
取所有字典的 keys 的集合的交集

from random import randint, sample

# 随机产生 3 场球赛的 进球人和数
s1 = {
    
    x: randint(1,4) for x in sample('abcdefg',randint(3,6))}
s2 = {
    
    x: randint(1,4) for x in sample('abcdefg',randint(3,6))}
s3 = {
    
    x: randint(1,4) for x in sample('abcdefg',randint(3,6))}

print(s1)
print(s2)
print(s3)


print(s1.keys() & s2.keys() & s3.keys())

6.如何让字典保持有序?

d = dict()

d['Jim']=(1.35)

d['Leo']=(2,37)

d['Bob']=(3,45)

for k in d:
    print(k)

方法:使用collections.OrderedDict

以OrderedDict替代字典Dict,依次将选手成绩存入OrderedDict。


from collections import OrderedDict

d = OrderedDict()

d['Jim']=(1.35)

d['Leo']=(2,37)

d['Bob']=(3,45)

for k in d:
    print(k)

7.如何实现用户的历史记录功能?

原始代码如下:

from random import randint

N = randint(0, 100)

def guess(k):
	if k == N:
		print('猜对了')
		return True
	elif k < N:
		print('猜小了')
	else:
		print('猜大了')
	return False

while True:
	line = input("please input a number:")
	if line.isdigit():
		k = int(line)
		if guess(k):
			break

我们希望保存最近 5 次猜的数字,之前的就被删除

解决方案:

使用容量为 n (本例中 n=5) 的队列存储历史记录
使用标准库中的 deque,它是一个双端循环队列

from random import randint
from collections import deque

history = deque([], 5)

N = randint(0, 100)

def guess(k):
	if k == N:
		print('猜对了')
		return True
	elif k < N:
		print('猜小了')
	else:
		print('猜大了')
	return False

while True:
	line = input("please input a number:")
	if line.isdigit():
		k = int(line)
		history.append(k)
		if guess(k):
			break
	elif line == 'history' or line == 'h?':
		print(history)

若我们还希望 程序下次运行时,可以查看之前的历史记录,就需要将 队列对象 保存到磁盘,可以使用 pickle

pickle 可以将任意类型的数据(包括 数字型、列表、字典、字符串等)保存到磁盘文件,在需要的时候还可以正常读回为原数据

解决方案:程序退出前,可以使用 pickle 将队列对象存入文件,再次运行程序时将其导入

pickle 的用法:

写数据:

import pickle

data = [1, 2, 3, 4]

with open('data.dat', 'wb') as f:

    pickle.dump(data, f)

读数据:

import pickle

with open('data.dat', 'rb') as f:

    data = pickle.load(f)

print(data)

总结

今天就是借助一些基础的代码案例,给大家分享讲解Python中的字典和集合在实际编程中的一些使用技巧,希望对您有所帮助!

猜你喜欢

转载自blog.csdn.net/weixin_61587867/article/details/132270140