A brief review of Python

Python Programming Review

Python basics

Features of python

bothCompiledandInterpretiveFeatures, a general-purpose programming language that considers procedural, functional and object-oriented programming paradigms

Interpreted languages ​​do not need to be compiled into machine code once and then run like compiled languages. Instead, a program called an interpreter dynamically converts the source code into machine code sentence by sentence for execution.

.py->.pyc

In pythonthe environment, Python will .pycstore the file __pycache__in the directory and add the Python version identification field to the file name.

When running the source file, Python will first look for the .pyc file in the corresponding location. After finding the .pyc, check whether there are any changes. If there are any changes, it needs to be recompiled into bytecode.

Python programs cannot be compiled into machine code at once. They are first converted into bytecode.pyc and then interpreted and executed by the python virtual machine.

pip package manager

pip help #列出pip的子命令
pip install <packkage>
pip install <package>==<version>
pip uninstall <package>
pip list

python script

#!/usr/bin/env python

Pay attention to conditional judgment statements

if __name__=='__main__'

__name__It is a built-in attribute of Python and a global system variable! Each py file has its own__name__

If the py file is imported as a module, then __name__it is the file name of the py file (also called the module name);

If the py file is run directly (Ctrl+Shift+F10), then __name__the default is equal to a string __main__;

Composite data type

list

A list is a collection of objects, the types of which can be different

In [1]: x=[1,3.14,"hello"]

In [2]: x
Out[2]: [1, 3.14, 'hello']

A list is also a mutable object, which means that its value can still be modified after the object is created.

list slicing

Use a colon to separate two subscripts, representing the starting subscript (inclusive) and the ending subscript (exclusive).

In [13]: x=[1,3.14,"hello"]

In [14]: a=x[0:-1]

In [15]: a
Out[15]: [1, 3.14]

List common methods

list.append(x)
list.extend(x) #将序列x中的所有元素依次添加至列表List的尾部
list.insert(index,x)#在列表指定位置插入对象x
list.pop([index])#删除尾部或者指定位置的元素
list.remove(x)#在列表中删除首次出现的指定元素x
list.clear#删除列表中的所有元素
list.index(x)#返回x元素的下标
list.count(x)#返回指定元素x的出现次数
list.sort()#对列表元素进行正序排列
list.reverse()
list.copy()#进行浅拷贝
In [22]: x
Out[22]: [1, 3.14, 'hello']

In [23]: x.append('world')
In [25]: x
Out[25]: [1, 3.14, 'hello', 'world']
In [26]: a=[1,2,3]

In [27]: x.extend(a)

In [28]: x
Out[28]: [1, 3.14, 'hello', 'world', 1, 2, 3]

list comprehension

In [29]: a=[i for i in [1,'2','3']]

In [30]: a
Out[30]: [1, '2', '3']
In [31]: [(i,j)for i in range(10) if i!=5 for j in range(3) if j>=2]
Out[31]: [(0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (6, 2), (7, 2), (8, 2), (9, 2)]

tuple

A tuple is a sequence of arbitrary objects and does not support in-place modification, that is, the tuple has been created and the elements in it cannot be changed in any way (immutable feature)

In [33]: x=(1,2,3)

In [34]: x
Out[34]: (1, 2, 3)

In [35]: y=tuple()

In [36]: y
Out[36]: ()

Note: Tuples have no sortsum reversemethod

But there are sortedand reversedmethods, which will return a new sequence object

In [56]: x=(1,2,3,(1,2),[1,2,3])

In [57]: x
Out[57]: (1, 2, 3, (1, 2), [1, 2, 3])

In [58]: x[4][0]=None

In [59]: x
Out[59]: (1, 2, 3, (1, 2), [None, 2, 3])
In [61]: x[4]=None
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-61-dd313a01e66b> in <module>
----> 1 x[4]=None

TypeError: 'tuple' object does not support item assignment

dictionary

Dictionaries are mutable key-value pairs集合

Immutable objects available as

In [75]: x=dict(zip(keys,values))

In [76]: x
Out[76]: {
    
    'name': 'lihua', 'age': 12}
In [83]: x.get('name')#获取对应的键的值
Out[83]: 'lihua'

In [84]: x.update({
    
    'gender':'male'})

In [85]: x
Out[85]: {
    
    'name': 'lihua', 'age': 12, 'gender': 'male'}

keys() values items()Corresponding to the keys, values ​​and objects of the dictionary respectively

Key-value pairs cannot be repeated

In fact, its key is not repeatable

gather

setA set is an unordered mutable sequence, {}delimited by a pair of curly braces, and no duplication is allowed.

>>> a={
    
    1,2,3}
>>> type(a)
<class 'set'>
In [110]: a
Out[110]: {
    
    1, 2, 3, 4}

In [111]: a.remove(5)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-111-fa8c667230ef> in <module>
----> 1 a.remove(5)

KeyError: 5

In [112]: a.discard(5)

In [113]: a
Out[113]: {
    
    1, 2, 3, 4}

Union, intersection and difference operations of sets

In [113]: a
Out[113]: {
    
    1, 2, 3, 4}
In [117]: s={
    
    1,3,5}

In [118]: a.union(s)
Out[118]: {
    
    1, 2, 3, 4, 5}

In [119]: a.intersection(s)
Out[119]: {
    
    1, 3}

In [120]: a.difference(s)
Out[120]: {
    
    2, 4}

Dark and shallow copy

Shallow copy appears in copy function and list slicing

If you want to copy the nesting each time, you need the deep copy function

Unicode and strings

Characters are the smallest components of text

A character set is a manually filtered collection of multiple characters.

Encoding rules are standards for converting characters in a character set into storable byte sequences.

UTF-8 variable length encoding scheme

If the code point is less than 127 (0x7f), it is represented by a single byte

The code point is 128-2047 two bytes

Greater than 2048 three or four

Chinese is usually compiled into three bytes

function

Parameter unpacking for passing real-time parameters

You can use iterable objects such as lists, tuples, dictionaries, etc. as actual parameters, and add a '*' in front of the actual parameter name.

In [174]: def func(a,b,c):
     ...:     print(a,b,c)
     ...:

In [175]: func(*[1,2,3])
1 2 3

If it is a dictionary object, you need to add '**' in front of it.

'*' and '**' if they appear in a function definition, they represent accepting any number of parameters, and if they appear in a function call, they represent parameter unpacking.

lambda expression

lambda arg1,arg2,...,argN:expression 

Executing a lambda expression will generate a function object, which can be assigned to a variable for subsequent calls. This is no different from using a def statement to define a function.

In [178]: f=lambda x, y: x + y

In [179]: f(1,2)
Out[179]: 3

Global variables and local variables

global keyword

Iterator

>>> m=map(lambda x:x**2,[1,2,3])
>>> it1=m.__iter__()
>>> it1 is m
True
>>> it1.__next__()
1
>>> it1.__next__()
4
>>> it1.__next__()
9
>>> it1.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
#斐波那契函数迭代器
class Fibs:
    def __init__(self,n=10):
        self.a=0
        self.b=1
        self.n=n
    def __iter__(self):
        return self
    def __next__(self):
        self.a,self.b=self.b,self.a+self.b
        if self.a>self.n:
            raise StopIteration
        return self.a

generator function

ALL

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_50925658/article/details/131975782