60 high-frequency writing methods in Python's daily work, collection

1. Numbers

1 Find the absolute value

absolute value or modulo of a complex number

In [1]: abs(-6)
Out[1]: 6

binary conversion

Decimal to binary conversion:

In [2]: bin(10)
Out[2]: '0b1010'

Convert decimal to octal:

In [3]: oct(9)
Out[3]: '0o11'

Decimal to hexadecimal:

In [4]: hex(15)
Out[4]: '0xf'

3 Conversion between integer and ASCII

The ASCII character corresponding to the decimal integer

In [1]: chr(65)
Out[1]: 'A'

View the decimal number corresponding to an ASCII character

In [1]: ord('A')
Out[1]: 65

4 elements are all true checks

Returns True if all elements are true, otherwise False

In [5]: all([1,0,3,6])
Out[5]: False
In [6]: all([1,2,3])
Out[6]: True

5 elements at least one is true check

Returns True if at least one element is true, otherwise False

In [7]: any([0,0,0,[]])
Out[7]: False
In [8]: any([0,0,1])
Out[8]: True

6 Judging whether it is true or false

Tests whether an object is True or False.

In [9]: bool([0,0,0])
Out[9]: True

In [10]: bool([])
Out[10]: False

In [11]: bool([1,0,1])
Out[11]: True

7 Create plurals

create a plural

In [1]: complex(1,2)
Out[1]: (1+2j)

8 Take quotient and remainder

Take the quotient and remainder separately

In [1]: divmod(10,3)
Out[1]: (3, 1)

9 Convert to floating point type

Converts an integer or numeric string to a floating point number

In [1]: float(3)
Out[1]: 3.0

If it cannot be converted to a floating point number, a ValueError will be reported:

In [2]: float('a')
# ValueError: could not convert string to float: 'a'

10 converted to an integer

int(x, base =10) , x may be a string or a number, convert x to an ordinary integer. If the argument is a string, it may contain symbols and decimal points. A long integer is returned if it exceeds the representation range of an ordinary integer.

In [1]: int('12',16)
Out[1]: 18

power of 11

Base is the power of exp, if mod is given, take the remainder

In [1]: pow(3, 2, 4)
Out[1]: 1

12 rounded

Rounding, ndigits represents how many digits are reserved after the decimal point:

In [11]: round(10.0222222, 3)
Out[11]: 10.022

In [12]: round(10.05,1)
Out[12]: 10.1

13 Chained comparisons

i = 3
print(1 < i < 3)  # False
print(1 < i <= 3)  # True

Two, the string

14 String to byte

string to byte type

In [12]: s = "apple"                                                            

In [13]: bytes(s,encoding='utf-8')
Out[13]: b'apple'

15 Convert any object to a string

In [14]: i = 100                                                                

In [15]: str(i)
Out[15]: '100'

In [16]: str([])
Out[16]: '[]'

In [17]: str(tuple())
Out[17]: '()'

16 Execute the code represented by the string

Compile the string into code that python can recognize or execute, or read the text into a string and then compile it.

In [1]: s  = "print('helloworld')"
    
In [2]: r = compile(s,"<string>", "exec")
    
In [3]: r
Out[3]: <code object <module> at 0x0000000005DE75D0, file "<string>", line 1>
    
In [4]: exec(r)
helloworld

17 Calculation expressions

Evaluate the string str as a valid expression and return the calculation result to extract the contents of the string

In [1]: s = "1 + 3 +5"
    ...: eval(s)
    ...:
Out[1]: 9

18 String Formatting

Format the output string, format(value, format_spec) essentially calls __format__(format_spec)the method of value.

In [104]: print("i am {0},age{1}".format("tom",18))
i am tom,age18

3.1415926	{
    
    :.2f}	3.14	保留小数点后两位
3.1415926	{
    
    :+.2f}	+3.14	带符号保留小数点后两位
-1	{
    
    :+.2f}	-1.00	带符号保留小数点后两位
2.71828	{
    
    :.0f}	3	不带小数
5	{
    
    :0>2d}	05	数字补零 (填充左边, 宽度为2)
5	{
    
    :x<4d}	5xxx	数字补x (填充右边, 宽度为4)
10	{
    
    :x<4d}	10xx	数字补x (填充右边, 宽度为4)
1000000	{
    
    :,}	1,000,000	以逗号分隔的数字格式
0.25	{
    
    :.2%}	25.00%	百分比格式
1000000000	{
    
    :.2e}	1.00e+09	指数记法
18	{
    
    :>10d}	' 18'	右对齐 (默认, 宽度为10)
18	{
    
    :<10d}	'18 '	左对齐 (宽度为10)
18	{
    
    :^10d}	' 18 '	中间对齐 (宽度为10)

3. Function

19 Out-of-the-box sort functions

Sort by:

In [1]: a = [1,4,2,3,1]

In [2]: sorted(a,reverse=True)
Out[2]: [4, 3, 2, 1, 1]

In [3]: a = [{
    
    'name':'xiaoming','age':18,'gender':'male'},{
    
    'name':'
     ...: xiaohong','age':20,'gender':'female'}]
In [4]: sorted(a,key=lambda x: x['age'],reverse=False)
Out[4]:
[{
    
    'name': 'xiaoming', 'age': 18, 'gender': 'male'},
 {
    
    'name': 'xiaohong', 'age': 20, 'gender': 'female'}]

20 Sum function

Summing:

In [181]: a = [1,4,2,3,1]

In [182]: sum(a)
Out[182]: 11

In [185]: sum(a,10) #求和的初始值为10
Out[185]: 21

21 nonlocal is used in built-in functions

The keyword nonlocal is often used in function nesting to declare the variable i as a non-local variable; if not declared, i+=1 indicates that i is a local variable in the function wrapper, because when i+=1 reference (reference), i is not declared , so an error of unreferenced variable will be reported.

def excepter(f):
    i = 0
    t1 = time.time()
    def wrapper():
        try:
            f()
        except Exception as e:
            nonlocal i
            i += 1
            print(f'{
      
      e.args[0]}: {
      
      i}')
            t2 = time.time()
            if i == n:
                print(f'spending time:{
      
      round(t2-t1,2)}')
    return wrapper

22 global Declare global variables

First answer why there is a global, a variable is referenced by multiple functions, and I want the global variable to be shared by all functions. Some partners may think that this is not easy, write like this:

i = 5
def f():
    print(i)

def g():
    print(i)
    pass

f()
g()

Both functions f and g can share the variable i, and the program does not report an error, so they still don't understand why global is used.

However, if I want to have a function that increments i like this:

def h():
    i += 1

h()

Execute the program at this time, bang, something went wrong! An exception is thrown: UnboundLocalError. It turns out that when the compiler interprets i+=1, it will resolve i as a local variable in the function h(). Obviously, in this function, the compiler cannot find the definition of the variable i, so it will report an error .

Global is proposed to solve this problem. In the function h, explicitly tell the compiler that i is a global variable, and then the compiler will look for the definition of i outside the function. After executing i+=1, i is still a global variable , adding 1 to the value:

i = 0
def h():
    global i
    i += 1

h()
print(i)

23 Swap two elements

def swap(a, b):
    return b, a


print(swap(1, 0))  # (0,1)

24 Manipulating function objects

In [31]: def f():
    ...:     print('i\'m f')
    ...:

In [32]: def g():
    ...:     print('i\'m g')
    ...:

In [33]: [f,g][1]()
i'm g

Create a list of function objects, according to the index you want to call, to facilitate unified calling.

25 Generating reverse sequence

list(range(10,-1,-1)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

When the third parameter is negative, it means to decrease from the first parameter and end to the second parameter (excluding this boundary)

26 Examples of the use of five types of parameters for functions

Python five types of parameters: positional parameters, keyword parameters, default parameters, use of variable positional or keyword parameters.

def f(a,*b,c=10,**d):
  print(f'a:{
      
      a},b:{
      
      b},c:{
      
      c},d:{
      
      d}')

The default argument c cannot come after the variadic keyword argument d.

call f:

In [10]: f(1,2,5,width=10,height=20)
a:1,b:(2, 5),c:10,d:{
    
    'width': 10, 'height': 20}

The variable positional parameter b is parsed as a tuple (2,5); and c gets the default value of 10; d is parsed as a dictionary.

call f again:

In [11]: f(a=1,c=12)
a:1,b:(),c:12,d:{
    
    }

When a=1 is passed in, a is a keyword parameter, b and d are not passed in value, and c is passed in 12 instead of the default value.

Pay attention to observe the parameter a, either f(1) or f(a=1), its readability is better than the first one, it is recommended to use f(a=1). If you want to force f(a=1), you need to add an asterisk in front:

def f(*,a,**b):
  print(f'a:{
      
      a},b:{
      
      b}')

At this time, when f(1) is called, an error will be reported: TypeError: f() takes 0 positional arguments but 1 was given

Only f(a=1) can be OK.

It shows that the previous * comes into play, and it can only pass in keyword parameters, so how to check the type of this parameter? With python's inspect module:

In [22]: for name,val in signature(f).parameters.items():
    ...:     print(name,val.kind)
    ...:
a KEYWORD_ONLY
b VAR_KEYWORD

It can be seen that the type of parameter a is KEYWORD_ONLY, that is, it is only a keyword parameter.

However, if f is defined as:

def f(a,*b):
  print(f'a:{
      
      a},b:{
      
      b}')

View parameter types:

In [24]: for name,val in signature(f).parameters.items():
    ...:     print(name,val.kind)
    ...:
a POSITIONAL_OR_KEYWORD
b VAR_POSITIONAL

You can see that the parameter a can be either a positional parameter or a keyword parameter.

27 Using the slice object

Generate the sequence cake1 about cakes:

In [1]: cake1 = list(range(5,0,-1))

In [2]: b = cake1[1:10:2]

In [3]: b
Out[3]: [4, 2]

In [4]: cake1
Out[4]: [5, 4, 3, 2, 1]

Generate another sequence:

In [5]: from random import randint
   ...: cake2 = [randint(1,100) for _ in range(100)]
   ...: # 同样以间隔为2切前10个元素,得到切片d
   ...: d = cake2[1:10:2]
In [6]: d
Out[6]: [75, 33, 63, 93, 15]

You see, we use the same cutting method to cut two cakes cake1 and cake2 respectively. Later, we found that this cutting method is very classic, and we used it to cut more container objects.

So, why not encapsulate this cut as an object? So there is a slice object.

Defining a slice object is extremely simple, such as defining the above cut method as a slice object:

perfect_cake_slice_way = slice(1,10,2)
#去切cake1
cake1_slice = cake1[perfect_cake_slice_way]
cake2_slice = cake2[perfect_cake_slice_way]

In [11]: cake1_slice
Out[11]: [4, 2]

In [12]: cake2_slice
Out[12]: [75, 33, 63, 93, 15]

Consistent with the above results.

For reverse sequence slicing, the slice object works just as well:

a = [1,3,5,7,9,0,3,5,7]
a_ = a[5:1:-1]

named_slice = slice(5,1,-1)
a_slice = a[named_slice]

In [14]: a_
Out[14]: [0, 9, 7, 5]

In [15]: a_slice
Out[15]: [0, 9, 7, 5]

Operations that frequently use the same slice can be extracted using the slice object, which can improve code readability while being reused.

28 Animated demos of lambda functions

Some readers reported that lambda functions are not very useful, and asked me if I could explain it.

For example, the following finds the lambda function:

def max_len(*lists):
    return max(*lists, key=lambda v: len(v))

There are two doubts:

The value of the parameter v?

Does a lambda function have a return value? If so, what is the return value?

Call the above function to find the following three longest lists:

r = max_len([1, 2, 3], [4, 5, 6, 7], [8])

print(f'更长的列表是{
      
      r}')

in conclusion:

The possible values ​​of parameter v are *lists, which is an element of tuple.

The return value of the lambda function is equal to the return value of the expression after the colon of lambda v.

4. Data structure

29 Convert to dictionary

Create data dictionary

In [1]: dict()
Out[1]: {
    
    }

In [2]: dict(a='a',b='b')
Out[2]: {
    
    'a': 'a', 'b': 'b'}

In [3]: dict(zip(['a','b'],[1,2]))
Out[3]: {
    
    'a': 1, 'b': 2}

In [4]: dict([('a',1),('b',2)])
Out[4]: {
    
    'a': 1, 'b': 2}

30 frozen collections

Create an unmodifiable collection.

In [1]: frozenset([1,1,3,2,3])
Out[1]: frozenset({
    
    1, 2, 3})

Because it is not modifiable, there are no add and pop methods like set

31 Convert to collection type

Returns a set object, and duplicate elements are not allowed in the set:

In [159]: a = [1,4,2,3,1]

In [160]: set(a)
Out[160]: {
    
    1, 2, 3, 4}

32 Convert to slice object

class slice(start, stop[, step])

Returns a slice object representing the index set specified by range(start, stop, step), which makes the code more readable and maintainable.

In [1]: a = [1,4,2,3,1]

In [2]: my_slice_meaning = slice(0,5,2)

In [3]: a[my_slice_meaning]
Out[3]: [1, 2, 1]

33 to tuple

tuple() converts an object into an immutable sequence type

In [16]: i_am_list = [1,3,5]
In [17]: i_am_tuple = tuple(i_am_list)
In [18]: i_am_tuple
Out[18]: (1, 3, 5)

5. Classes and Objects

34 Is it callable

Checks whether the object can be called

In [1]: callable(str)
Out[1]: True
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078
In [2]: callable(int)
Out[2]: True
In [18]: class Student():
    ...:     def __init__(self,id,name):
    ...:         self.id = id
    ...:         self.name = name
    ...:     def __repr__(self):
    ...:         return 'id = '+self.id +', name = '+self.name
    ...

In [19]: xiaoming = Student('001','xiaoming')

In [20]: callable(xiaoming)
Out[20]: False

If you can call xiaoming(), you need to rewrite the __call__ method of the Student class:

In [1]: class Student():
    ...:     def __init__(self,id,name):
    ...:         self.id = id
    ...:         self.name = name
    ...:     def __repr__(self):
    ...:         return 'id = '+self.id +', name = '+self.name
    ...:     def __call__(self):
    ...:         print('I can be called')
    ...:         print(f'my name is {
      
      self.name}')
    ...:

In [2]: t = Student('001','xiaoming')

In [3]: t()
I can be called
my name is xiaoming

35 ascii display objects

Call the repr method of the object to obtain the return value of the method. The return value of the following example is a string

>>> class Student():
    def __init__(self,id,name):
        self.id = id
        self.name = name
    def __repr__(self):
        return 'id = '+self.id +', name = '+self.name

transfer:

>>> xiaoming = Student(id='1',name='xiaoming')
>>> xiaoming
id = 1, name = xiaoming
>>> ascii(xiaoming)
'id = 1, name = xiaoming'

36 class methods

The function corresponding to the classmethod decorator does not need to be instantiated and does not need the self parameter, but the first parameter needs to be the cls parameter representing its own class, which can be used to call the class's attributes, methods, and instantiated objects.

In [1]: class Student():
    ...:     def __init__(self,id,name):
    ...:         self.id = id
    ...:         self.name = name
    ...:     def __repr__(self):
    ...:         return 'id = '+self.id +', name = '+self.name
    ...:     @classmethod
    ...:     def f(cls):
    ...:         print(cls)

37 Dynamically delete attributes

delete object properties

In [1]: delattr(xiaoming,'id')

In [2]: hasattr(xiaoming,'id')
Out[2]: False

38 View all methods of an object with one click

When there is no parameter, it returns the variable, method and defined type list in the current scope; when there is a parameter, it returns the attribute and method list of the parameter.

In [96]: dir(xiaoming)
Out[96]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 
 'name']

39 Obtain object properties dynamically

Get the properties of the object

In [1]: class Student():
   ...:     def __init__(self,id,name):
   ...:         self.id = id
   ...:         self.name = name
   ...:     def __repr__(self):
   ...:         return 'id = '+self.id +', name = '+self.name

In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: getattr(xiaoming,'name') # 获取xiaoming这个实例的name属性值
Out[3]: 'xiaoming'

40 Whether the object has this attribute

In [1]: class Student():
   ...:     def __init__(self,id,name):
   ...:         self.id = id
   ...:         self.name = name
   ...:     def __repr__(self):
   ...:         return 'id = '+self.id +', name = '+self.name

In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: hasattr(xiaoming,'name')
Out[3]: True

In [4]: hasattr(xiaoming,'address')
Out[4]: False

41 Object house number

Returns the memory address of the object

In [1]: id(xiaoming)
Out[1]: 98234208

42 isinstance

Determine whether the object is an instance of the class classinfo, and return true

In [1]: class Student():
   ...:     def __init__(self,id,name):
   ...:         self.id = id
   ...:         self.name = name
   ...:     def __repr__(self):
   ...:         return 'id = '+self.id +', name = '+self.name

In [2]: xiaoming = Student(id='001',name='xiaoming')

In [3]: isinstance(xiaoming,Student)
Out[3]: True

43 Identification of paternity

In [1]: class undergraduate(Student):
    ...:     def studyClass(self):
    ...:         pass
    ...:     def attendActivity(self):
    ...:         pass

In [2]: issubclass(undergraduate,Student)
Out[2]: True

In [3]: issubclass(object,Student)
Out[3]: False

In [4]: issubclass(Student,object)
Out[4]: True

Also returns True if class is a subclass of an element in the classinfo tuple

In [1]: issubclass(int,(int,float))
Out[1]: True

44 The root of all objects

object is the base class of all classes

In [1]: o = object()

In [2]: type(o)
Out[2]: object

45 Two ways to create properties

Return the property attribute, typical usage:

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

# 使用property类创建 property 属性
x = property(getx, setx, delx, "I'm the 'x' property.")

Use the python decorator to achieve exactly the same effect code as above:

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

46 View Object Type

class type(name, bases, dict)

When a parameter is passed in, the type of object is returned:

In [1]: class Student():
   ...:     def __init__(self,id,name):
   ...:         self.id = id
   ...:         self.name = name
   ...:     def __repr__(self):
   ...:         return 'id = '+self.id +', name = '+self.name
   ...:

In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: type(xiaoming)
Out[3]: __main__.Student

In [4]: type(tuple())
Out[4]: tuple

47 Metaclasses

xiaoming, xiaohong, xiaozhang are all students, this group is called Student.

A common way to define classes in Python, using the keyword class

In [36]: class Student(object):
    ...:     pass
xiaoming, xiaohong, xiaozhang 是类的实例,则:

xiaoming = Student()
xiaohong = Student()
xiaozhang = Student()

After creation, __class__the property of xiaoming returns the Student class

In [38]: xiaoming.__class__
Out[38]: __main__.Student

The problem is, the Student class has __class__properties, and if so, what are they returning?

In [39]: xiaoming.__class__.__class__
Out[39]: type

Wow, the program did not report an error, return type

Then, we might as well guess: the Student class, the type is type

In other words, the Student class is an object whose type is type

So, everything in Python is an object, and classes are also objects

In Python, the class that will describe the Student class is called: a metaclass.

According to this logical extension, the class that describes the metaclass is called: metametaclass, just kidding~ The class that describes the metaclass is also called a metaclass.

Smart friends will ask, since the Student class can create instances, can the type class create instances? If it can, the instance it creates is called: class. You are so smart!

That's right, the type class must be able to create instances, such as the Student class.

In [40]: Student = type('Student',(),{
    
    })

In [41]: Student
Out[41]: __main__.Student

It is identical to the Student class created using the class keyword.

Since Python classes are objects, they are similar to xiaoming and xiaohong objects. support:

  • assignment

  • copy

  • add attribute

as a function parameter

In [43]: StudentMirror = Student # 类直接赋值 # 类直接赋值
In [44]: Student.class_property = 'class_property' # 添加类属性
In [46]: hasattr(Student, 'class_property')
Out[46]: True

Metaclasses are indeed not used so much. Maybe you can deal with some occasions by understanding these first. Even the leader of the Python community, Tim Peters, said:

"Metaclasses are deep magic, and 99% of users shouldn't have to worry about it at all.

6. Tools

48 enumeration objects

Returns an enumerable object whose next() method will return a tuple.

In [1]: s = ["a","b","c"]
    ...: for i ,v in enumerate(s,1):
    ...:     print(i,v)
    ...:
1 a
2 b
3 c

49 View the number of bytes occupied by variables

In [1]: import sys

In [2]: a = {
    
    'a':1,'b':2.0}

In [3]: sys.getsizeof(a) # 占用240个字节
Out[3]: 240

50 filters

Set the filter condition in the function, iterate over the elements, and keep the element whose return value is True:

In [1]: fil = filter(lambda x: x>10,[1,11,2,45,7,6,13])

In [2]: list(fil)
Out[2]: [11, 45, 13]

51 returns the hash value of the object

Returns the hash value of the object. It is worth noting that custom instances are all hashable, and mutable objects such as list, dict, and set are all unhashable (unhashable)

In [1]: hash(xiaoming)
Out[1]: 6139638

In [2]: hash([1,2,3])
# TypeError: unhashable type: 'list'

52 One-click help

Returns the help documentation for the object

In [1]: help(xiaoming)
Help on Student in module __main__ object:

class Student(builtins.object)
 |  Methods defined here:
 |
 |  __init__(self, id, name)
 |
 |  __repr__(self)
 |
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)

53 Get user input

Get user input

In [1]: input()
aa
Out[1]: 'aa'

54 Creating Iterator Types

Use iter(obj, sentinel), return an iterable object, sentinel can be omitted (once iterated to this element, terminate immediately)

In [1]: lst = [1,3,5]

In [2]: for i in iter(lst):
    ...:     print(i)
    ...:
1
3
5
In [1]: class TestIter(object):
    ...:     def __init__(self):
    ...:         self.l=[1,3,2,3,4,5]
    ...:         self.i=iter(self.l)
    ...:     def __call__(self):  #定义了__call__方法的类的实例是可调用的
    ...:         item = next(self.i)
    ...:         print ("__call__ is called,fowhich would return",item)
    ...:         return item
    ...:     def __iter__(self): #支持迭代协议(即定义有__iter__()函数)
    ...:         print ("__iter__ is called!!")
    ...:         return iter(self.l)
In [2]: t = TestIter()
In [3]: t() # 因为实现了__call__,所以t实例能被调用
__call__ is called,which would return 1
Out[3]: 1
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078
In [4]: for e in TestIter(): # 因为实现了__iter__方法,所以t能被迭代
    ...:     print(e)
    ...:
__iter__ is called!!
1
3
2
3
4
5

55 Open file

return file object

In [1]: fo = open('D:/a.txt',mode='r', encoding='utf-8')

In [2]: fo.read()
Out[2]: '\ufefflife is not so long,\nI use Python to play.'

mode value table:

character significance
r read (default)
w write, and truncate the file first
x Create exclusively, fail if file already exists
a write, append at the end if the file exists
b binary mode
t text mode (default)
+ open for update (read and write)

56 Create a range sequence

range(stop)

range(start, stop[,step])

Generate an immutable sequence:

In [1]: range(11)
Out[1]: range(0, 11)

In [2]: range(0,11,1)
Out[2]: range(0, 11)

57 reverse iterator

In [1]: rev = reversed([1,4,2,3,1])

In [2]: for i in rev:
     ...:     print(i)
     ...:
1
3
2
4
1

58 aggregate iterator

Create an iterator that aggregates the elements from each iterable:

In [1]: x = [3,2,1]
In [2]: y = [4,5,6]
In [3]: list(zip(y,x))
Out[3]: [(4, 3), (5, 2), (6, 1)]

In [4]: a = range(5)
In [5]: b = list('abcde')
In [6]: b
Out[6]: ['a', 'b', 'c', 'd', 'e']
In [7]: [str(y) + str(x) for x,y in zip(a,b)]
Out[7]: ['a0', 'b1', 'c2', 'd3', 'e4']

59 chain operation

from operator import (add, sub)


def add_or_sub(a, b, oper):
    return (add if oper == '+' else sub)(a, b)


add_or_sub(1, 2, '-')  # -1

60 object serialization

Object serialization refers to the process of converting objects in memory into storable or transferable ones. In many scenarios, it is inconvenient to transfer directly to a class object.

However, when the object is serialized, it will be more convenient, because by convention, calls between interfaces or web requests initiated are generally transmitted using json strings.

In actual use, class objects are generally serialized. First create a Student type, and create two instances.

class Student():
    def __init__(self,**args):
        self.ids = args['ids']
        self.name = args['name']
        self.address = args['address']
xiaoming = Student(ids = 1,name = 'xiaoming',address = '北京')
xiaohong = Student(ids = 2,name = 'xiaohong',address = '南京')

Import the json module and call the dump method to serialize the list object [xiaoming,xiaohong] into the file json.txt.

import json

with open('json.txt', 'w') as f:
    json.dump([xiaoming,xiaohong], f, default=lambda obj: obj.__dict__, ensure_ascii=False, indent=2, sort_keys=True)

The content of the generated file is as follows:

[
    {
    
    
        "address":"北京",
        "ids":1,
        "name":"xiaoming"
    },
    {
    
    
        "address":"南京",
        "ids":2,
        "name":"xiaohong"
    }
]

Guess you like

Origin blog.csdn.net/Python_222/article/details/129384315