Python-dictionary and collection programming tips

Hello, here is Token_w's blog, welcome to come.
Today I will mainly explain the usage skills of Python dictionaries and sets in actual programming.
It is not easy to organize, and it will be helpful to you. I hope to get your support! grateful! ! !

1. How to filter data according to conditions in lists, dictionaries, and collections?

actual case

  • Case 1: Filter out negative numbers in the list [3, 9, -1, 10, 20, -2, …]
  • Case 2: Filter out the items whose value is higher than 90 in the dictionary {'lisi': 79, 'Jin': 88, 'lucy': 93, … }
  • Case 3: It is relatively simple to screen out the elements in the set {77, 89, 34, 20, 21…} that can be divisible by 3. The
    usual method is to iterate each item in the list, dictionary, and set in turn, and perform the condition judge.

But in python, there are more advanced ways to solve this kind of problem, and it is simpler and more efficient.

01 Case 1: Filter out negative numbers in the list [3, 9, -1, 10, 20, -2, …]

Method 1: Use the filter function

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)

Method 2: Use a list comprehension

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 Case 2: Screen out items whose value is higher than 90 in the dictionary {'lisi': 79, 'Jin': 88, 'lucy': 93, … }

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 Case 3: Screen out the elements divisible by 3 in the set {77, 89, 34, 20, 21...}

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. How to name each element in the tuple to improve program readability?

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

01 Method 1: Define an enumeration type similar to other languages, that is, define a series of numeric constants

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 Method 2: Use collections.namedtuple in the standard library to replace the built-in 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. How to count the frequency of occurrence of elements in the sequence?

Case 1:

Method 1: Traditional method

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)

Method 2: Use collections.Counter object

Pass the sequence into the constructor of Counter, and get the Counter object as a dictionary of element frequencies
Counter.most_common(n) method gets the list of n elements with the highest frequency

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名

Case 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. How to sort the items in the dictionary according to the size of the values ​​in the dictionary?

01 Method 1: Use zip to convert dictionary data into tuples

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 Method 2: Use the key parameter of the sorted function

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. How to quickly find common keys in multiple dictionaries?

01 Method 1: traditional method, traverse in turn

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 Method 2: Use the intersection operation of the set (set)

Use the keys() method of the dictionary to get a set of keys of a dictionary
Take the intersection of the sets of keys of all dictionaries

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. How to keep the dictionary in order?

d = dict()

d['Jim']=(1.35)

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

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

for k in d:
    print(k)

Method: use collections.OrderedDict

Replace the dictionary Dict with OrderedDict, and store the players' scores in OrderedDict in turn.


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. How to implement the user's history record function?

The original code is as follows:

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

We want to save the last 5 guesses, the previous ones are deleted

solution:

Use a queue with a capacity of n (n=5 in this example) to store history
Use deque from the standard library, which is a double-ended circular queue

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)

If we also want to view the previous history when the program runs next time, we need to save the queue object to disk, and we can use pickle

pickle can save any type of data (including numbers, lists, dictionaries, strings, etc.) to disk files, and can be read back as original data when needed

Solution: Before the program exits, you can use pickle to store the queue object in a file, and import it when you run the program again

Usage of pickle:

Write data:

import pickle

data = [1, 2, 3, 4]

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

    pickle.dump(data, f)

Read data:

import pickle

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

    data = pickle.load(f)

print(data)

Summarize

Today, with the help of some basic code cases, I will share with you some tips on how to use dictionaries and sets in Python in actual programming. I hope it will be helpful to you!

Guess you like

Origin blog.csdn.net/weixin_61587867/article/details/132270140