This is the 20th day of my participation in the First Challenge 2022

Python little knowledge

Recently, I have been watching “Learning Python without Stress” to consolidate my basic knowledge. I accidentally learned a lot of common but not always noticed small knowledge. I share it with you

Click here for the first Python tips. Click here for the second Python tips

Dictionaries and collections

(1) a dictionary

Dict is a common data structure in Python. The basic format is {key: values}. Keys and values can be of any type, such as int, STR, etc.

Key values that can be easily indexed by key
dict_test = {'name':'XksA'.'age':22}
print('Name:'+dict_test['name'])
print('Age:'+str(dict_test['age']))
"Result: name: XksA Age: 22"

Dictionary traversal
dict_test = {'name':'XksA'.'age':22}

for k,v in dict_test.items():
	print(k + ':' + str(v))

''' result: name:XksA age:22 '''
dict_test = {'name':'XksA'.'age':22}
# take key
for k in dict_test.keys():
	print(k)
print('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --')
# select key only
for v in dict_test.values():
	print(str(v))

''' result: name age ------------------- XksA 22 '''
Copy the code

(2) set

In Python, sets, which can be created using curly braces {} or set(), can be called special lists and cannot contain duplicate elements. Note also that to create an empty set, you must use set() instead of {}, because {} is used to create only dictionaries, and the system defaults to empty dictionaries.

Set basic operations
set_test = {1.2.3.4.5.6}
# add
set_test.add('XksA')
print('After adding:'+str(set_test))
# remove
set_test.remove(2)
print('After deletion:'+str(set_test))
# Find intersection, union, difference set
set_a = {1.2.3.4}
set_b = {3.4.5.6}
print('Intersection of a/ B:'+str(set_a & set_b))
print('Union of a/b:'+str(set_a | set_b))
print('Difference set of a/b:'+str(set_a - set_b))

''' result: After adding: {1, 2, 3, 4, 5, 6, 'XksA} after the delete: {1, 3, 4, 5, 6,' XksA} at the intersection between a/b: {3, 4} and set a/b: {1, 2, 3, 4, 5, 6} a/b difference set: {1, 2} ' ' '
Copy the code

Note: Sets are unordered, do not support sorting, and do not support indexing, as follows:

Print (set_B [2]) TypeError: 'Set' object does not support indexingCopy the code

(3) Small skills, fuzzy search

# Dictionary-based fuzzy lookup
dict_txl = {'Mr.Zhang':'15799991234'.'Mr.XksA':'85320211'.'Miss. Minimalist':'5220502'
            ,'WangW':'121331331'.'ZhangS':'121331331'}
while(True):
	str_name = input("Enter the name of the person you want to search for (fuzzy search) :")
	for k,v in dict_txl.items():
		if k.startswith(str_name):
			print(k + ':' + v)
	i = input("Do you want to continue looking for (y/n? :")
	if i == 'n':
		break

Result: enter the name of the person you want to find (y/n) : Z ZhangS:121331331 : y enter the name of the person to search for (fuzzy search) : Miss Miss. Minimalist :5220502 Do you want to continue to search (y/n?) : y Enter the name of the person to be searched (fuzzy search) : M Mr.Zhang:15799991234 Mr.XksA:85320211 Miss. Minimalist :5220502 Whether to continue to find (y/n?) : n ' ' '
Copy the code

The startswith function checks if a string begins with a specified substring and returns True if it does, or False otherwise. If the arguments beg and end specify values, check within the specified range. Parameter Description Startswith (STR, beg,end)

STR -- the string to be detected. Beg -- Optional argument to set the starting position for string detection. End - Optional argument to set the end of string detection.Copy the code

Classes and objects

(1) Basic introduction

It says, “Believe it or not, you’ve been using Python objects since you started reading this book,” and I’m like, totally fine. Do you have objects?

Almost forgot, I this is a small skill, not too detailed to talk about these theoretical things, the following picture briefly introduced the class and object, feel good point praise oh ~

(2) Create class, create object, call class method

# create classes
class Myclass() :
	Create a class variable
	my_variable = 'the minimalist XksA'
	Create a class function
	def my_function(self) :
		print("hello world!")

Create class object
my_object = Myclass()
Call a class variable
print(my_object.my_variable)
Call the class function
my_object.my_function()
"Result: Minimalist XksA hello world! ' ' '
Copy the code

(3) The most important __init__() function

Reserved words in Python begin and end with “__”.

Method __init__ is one of the most important methods in a class. As the name suggests, this means initialization. When creating a class object, this method is called automatically, passing arguments to class variables.

# create classes
class Myclass() :
	Create a class variable
	my_variable = 'the minimalist XksA'
	Initialize the function
	def __init__(self,input_variable) :
		# change my_variable value
		self.my_variable = input_variable
		print("hello world!")

Create class object, pass parameter
my_object = Myclass('class')
Call a class variable
print(my_object.my_variable)

''' result : hello world! Class ' ' '
Copy the code

Iii. Generator

In Python, the mechanism for calculating as you loop is called a Generator.

You can also think of a generator as an object that iterates automatically, similar to but more flexible than a for loop.

Generate Fibonacci sequence
def get_fibos(n) :
Generate Fibonacci numbers based on n. The number of Fibonacci numbers generated depends on n. For example, if n = 10, 10 Fibonacci numbers will be generated once.
	a = b = 1
	i = 0 
	while i < n :
		i = i + 1
		a,b = a+b , a
		print(a)

# Change to generator
def get_fibos(n) :
If the yield function is executed to the yield statement, it stops the run and returns the yield argument or statement.
	a = b = 1
	i = 0
	while i < n:
		i = i + 1
		a, b = a + b, a
		yield a
t0 = get_fibos(10)
print(t0)
for i in t0:
	print(i)
result :
	<generator object get_fibos at 0x0000021D112FC5C8>
	2
	3
	5
	8
	13
It is obvious that t0 is a generator, iterable.
Copy the code

According to the above, we learned that the generator is roughly one iteration of the object, with the yield keyword can be realized, has said the function performs to yield statements above, will stop the operation, after the return to yield parameters or statements, such as next time this function is called, will start where the last suspended continue running iteration, you will want to, So what exactly does a generator do?

Let’s look at another example:

Generate odd numbers in the integer range
def get_odd_num() :
	i = 1
	while True:
		yield i
		i += 2
Copy the code

To generate odd numbers in the integer range, a lot of people say, well, I can just generate them, so why use yield instead of generator? Have you ever thought that even though there is a range of odd numbers in integers, there are still a lot of them? How do you store them? The advantage of the generator is, how many you need, or which one you need, need which one, I will give you find this number, as long as to the number, then I stopped to have a rest, when you want to find another next time, I keep looking, and then again the same find rest, so that we don’t have to consider, so most put which place.

One more high-level example to close:

# Generate your own random number
from time import time
def get_rand() :
	# Select two large prime numbers at random
	p1 = 1200556037
	p2 = 2444555677
	# limit the maximum random number range
	max_rand = 2**32
	# get random number seed
	r0 = int(time()*1000)
	while True:
		# Loop to generate random numbers
		n = r0
		n *= p2
		n %= p1 # Enhance randomness for the first time
		
		n += r0
		
		n *= p2
		n %= p1 # Increase randomness the second time

		n %= max_rand # control random number range
		r0 = n
		yield n
Copy the code

To generate a random number, we first need to have a seed of random number (initial value), and then perform some random operations on the initial value. Here, we use expansion (multiplied by a prime number), return to the original (mod with another prime number), and do this repeatedly twice. Finally, we get the final random number by mod with max_rand. Such a SAO operation to ensure the randomness of the data, the middle operation to design to just right, more difficult, like the cryptography teacher said, “you encrypt, and encrypt, encrypt again, and encrypt again is likely to finally come out of the plaintext.”

Finally, the __next__() function, as shown in the first example, iterates through the for loop, as does the built-in __next__ function, which is called to call the next one, as shown in this example:

# fibos number
def get_fibos(n) :
   a = b = 1
   i = 0
   while i < n:
   	i = i + 1
   	a, b = a + b, a
   	yield a
t0 = get_fibos(5)
print(t0.__next__())
print(t0.__next__())

''' result : 2 3 '''
Copy the code

Generator is to my biggest feeling is, I in the process of using, need not consider too much, these data may overflow, or how, let me more think I will realize the function of how to design beautiful, see more, hit the sample code above, can understand, don’t expect to see it again, can understand and don’t catch hair by watching them, the leisure time to get out, Knock more code, watch movies, chat, listen to music, read a book… (More on that, see you next time: Decorators)

Apply these basic operations flexibly to your work and study.

Persistence and hard work: results.

Like to see the message forwarding, four support, the original is not easy. Ok, see you next time, I love the cat love technology, more love si si’s old cousin Da Mian ଘ(˙꒳˙)ଓ Di Di