This is the 19th 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
1. Derivation
List derivations are a basic, useful, and very important feature of Python, and one of the most popular Python features. In essence, list comprehensions can be understood as a process of converting one list into another through a function that combines transformation and filtering functions.
(1) Ordinary derivation
# Simple list derivation
list_test = [i for i in range(5)]
print(list_test)
Generate an even number (between 1 and 10)
list_test = [i for i in range(1.11) if i%2= =0]
print(list_test)
Generate an odd number (between 1 and 10)
list_test = [i for i in range(1.11) if i%2! =0]
print(list_test)
# Generate squares (between 1 and 10)
list_test = [pow(i,2) for i in range(1.11)]
print(list_test)
''' result: [0, 1, 2, 3, 4] [2, 4, 6, 8, 10] [1, 3, 5, 7, 9] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] '''
Copy the code
(2) Two-dimensional derivation
# 2-19 All composite numbers
list_test0 = {j for i in range(2.20) for j in range(i*i,20,i)}
print(list_test0)
# 2-19 All prime numbers
list_test1 = [i for i in range(2.20) if i not in list_test0]
print(list_test1)
''' result: {4, 6, 8, 9, 10, 12, 14, 15, 16, 18} [2, 3, 5, 7, 11, 13, 17, 19] '''
Copy the code
There are also dictionary, tuple, and set derivations in Python, which are used in much the same way as list derivations.
The use of list derivation is very extensive, from the practical experience, the use of list derivation is very high frequency, but also quite easy to use. However, for multi-layer FOR loops with complex filtering conditions, it is not good to use the list derivation, because it saves the code, but also makes it more difficult to read and understand. In this case, it is recommended to directly implement multiple ordinary FOR loops.
Enumerate and format functions
(1) enumerate function
The enumerate() function combines an iterable data object (such as a list, tuple, or string) into an index sequence that lists both data and data subscripts. It is typically used in a for loop. enumerate(sequence, start=0)
Sequence -- A sequence, iterator, or other object that supports iteration. Start -- the starting subscript position, 0 by default.Copy the code
- The basic use
list_test = ['hello'.'world'.'! ']
for i in enumerate(list_test):
# print(type(i)) result :
print(i)
result :
(0.'hello')
(1.'world')
(2.'! ')
' ' 'Copy the code
As can be seen from the above, the single object iterated after enumeration is a tuple.
- Indexes are separated from values
for index,values in enumerate(list_test):
# note: I used STR () to convert index to STR because index is int
print(str(index)+':'+values)
result :
0:hello
1:world
2:!
Copy the code
(2) the format function
A string formatting function that enhances the function of string formatting. The basic syntax is to replace the previous % with {} and:.
The format function can take unlimited arguments and positions out of order.
- Basic operation
# do not set the specified location, in default order
str_test0 = 'how are you {} {}! '.format(', '.'the minimalist XksA')
print(str_test0)
"Result: Hello, minimalist XksA! ' ' '
# set the specified location, in default order
str_test1 = 'Hell0{1}{0}! '.format('XksA'.', ')
print(str_test1)
''' result: Hell0,XksA! ' ' '
Parse dictionary parameters
dict_test = {'name':'XksA'.'age':21}
str_test2 = 'I am {name}, this year {age}! '.format(**dict_test)
print(str_test2)
"Result: I am XksA and I am 21 years old! ' ' '
# Select list/tuple parameters
list_test = ['you'.'XksA'] # ('you','XksA')
str_test3 = 'Do {0[0]} like {0[1]}? '.format(list_test)
print(str_test3)
''' result: Do you like XksA? ' ' '
Copy the code
- Format operations
table_head = ['id'.'name'.'age']
content = [[1.'XksA'.21], [2.'Python'.17], [3.'Java'.13]]
head = '{8} 0 [0] : ^ {8} 0 [1] : ^ {8} 0 [2] : ^'.format(table_head)
print(head)
for i in content:
content_test = '{8} 0 [0] : ^ {8} 0 [1] : ^ {8} 0 [2] : ^'.format(i)
print(content_test)
''' result : id name age 1 XksA 21 2 Python 17 3 Java 13 '''
Copy the code
- Syntax parsing
Format is set | Basic meaning |
---|---|
{:>n} | Set the field width to n and align the field to the left when it prints |
{:<n} | Set the field width to N and align the field to the right when it is printed |
{:^n} | Set the field width to n and center the field when printed |
3. File operation
(1) the open function
The Python open() function opens a file and creates a file object that can be called by related methods to read or write. open(name, mode, buffering)
Nam is mandatory. Other parameters are optional
Name: A string value containing the name of the file you want to access. Mode: Mode determines the mode of opening a file: read only, write, append, etc. All available values are shown in the complete list below. This parameter is optional, and the default file access mode is read-only (r). Buffering: If buffering is set to 0, there will be no storage. If buffering is 1, rows will be stored when the file is accessed. If buffering is set to an integer greater than 1, it indicates that this is the size of the host buffer. If the value is negative, the buffer size of the host area is the system default.Copy the code
(2) Read and write files
A. Contents of the original document:
B. File directory: I:\123.txt
C. read the file
with open(r'I:\123.txt') as file:
# to read file
content = file.read()
print(content)
''' result : hello world! I'm from China! ' ' '
Copy the code
Note: the IO stream can also be generated directly by open, without using with, but must remember to close the IO stream to avoid resource waste.
D. write files
with open(r'I:\123.txt',mode='r+') as file:
# write files
file.write('Welcome to minimalist XksA,Python Learning paradise ~')
Read it after you've written it
content = file.read()
print(content)
"Result: Welcome to minimalist XksA,Python learning park ~"
Copy the code
Note: When writing a file, note that the write format must be marked with “A +”,” R +”,” WB +”, or the file cannot be written. If the mode is not changed, the default value is” R “, and the file is read-only. IO.UnsupportedOperation: not writable will be reported when writing the file forcibly.
(3) Basic read and write format table
Local variables and global variables
(1) Local and global variables
A local variable is only valid for the function in which the variable resides. It does not affect or modify variables with the same name outside the function, so it can be considered that local variables are used before global variables. Example:
g_test = 10
def sum() :
a0 = 9
g_test = 10-a0
print("Local variable g_test has the value:"+str(g_test))
sum(a)print("The value of the global variable g_test is:"+str(g_test))
Result: local variable g_test: 1 global variable g_test: 10
Copy the code
It is obvious that the function field is not the same as the global field g_test. Although we changed the value of g_test in sum, we did not change the global variable g_test.
(2) the global keyword
In addition, global does not create the specified variable, so we still need to create the variable somewhere. We can assign the variable definition in the global field, or we can assign the definition in the function field. Example:
g_test = 10 # global variables
def sum() :
global g_test G_test is a global variable
g_test = 4 # global variables
print("G_test in the function field is:"+str(g_test))
sum(a)print("G_test in the global field is:"+str(g_test))
Result: g_test = 4 in the function field
Copy the code
It is obvious that the function field is now the same as the global field g_test, meaning that we can manipulate global variables in the function.
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