Hi, I’m Chi Ye

Today, I’m going to show you some basic python examples to help you remember. Here are 52 examples

1 finding absolute value

Magnitude of absolute value or complex number

In [1]: abs(-6)
Out[1]: 6
Copy the code

The two elements are all true

Accepts an iterator that returns True if all elements of the iterator are True, False otherwise

In [2] : all (,0,3,6 [1]) Out [2] : False In [3] : all ([1, 2, 3]) Out [3] : TrueCopy the code

At least one of the 3 elements is true

Accepts an iterator, returning True if at least one element in the iterator is True, False otherwise

In [4] : any ([0, 0, []]) Out [4] : False In [5] : any ([0, 1]) Out [5] : TrueCopy the code

4 ASCII Display object

Call the __repr__() method of the object and get the return value of the method, which is a string in the following example

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]: print(xiaoming) id = 001, name = xiaoming In [4]: ascii(xiaoming) Out[4]: 'id = 001, name = xiaoming'Copy the code

5十 turn 2

Convert decimal to binary

In [1]: bin(10)
Out[1]: '0b1010'
Copy the code

Patriarch turned eight

Convert decimal to octal

In [1]: oct(9)
Out[1]: '0o11'
Copy the code

Seven ten to sixteen

Convert decimal to hexadecimal

In [1]: hex(15)
Out[1]: '0xf'
Copy the code

8 Determine whether it is true or false

Tests whether an object is True or False.

In [1] : bool (0, 0) Out [1] : True In [2] : bool ([]) Out [2] : False In [3] : bool ([1, 1]) Out [3] : TrueCopy the code

9 String to bytes

Converts a string to a byte type

In [1]: s = "apple"

In [2]: bytes(s,encoding='utf-8')
Out[2]: b'apple'
Copy the code

10 Converting to a String

Converts character types, numeric types, and so on to string types

In [1]: i = 100

In [2]: str(i)
Out[2]: '100'
Copy the code

11 Check whether it can be called

Callable (STR, int, etc.); example 4: Xiaoming is not callable.

In [1]: callable(str)
Out[1]: True

In [2]: callable(int)
Out[2]: True

In [3]: xiaoming
Out[3]: id = 001, name = xiaoming

In [4]: callable(xiaoming)
Out[4]: False
Copy the code

If you want xiaoming() to be called, you need to override Student’s __call__ method:

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 xiaomingCopy the code

120 turn ASCII

View the ASCII characters of a decimal integer

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

13 turn ten ASCII

View the decimal number of an ASCII character

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

14 Static Methods

The function corresponding to the classMethod decorator does not need to be instantiated, does not need to take the self argument, but the first argument needs to be the CLS argument representing its own class, can call the class properties, class methods, instantiated objects, etc.

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)Copy the code

15 Executes the code represented by a string

Compile the string into code that Python recognizes or can execute, or read the text as 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
Copy the code

16 Creating complex Numbers

Create a complex number

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

17 Dynamically delete attributes

Deletes an attribute of an object

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

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

18 Turn into a dictionary

Creating a 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} [4] : In dict ([(' a ', 1), (" b ", 2)]) Out [4] : {' a ', 1, 'b' : 2}Copy the code

19 View all object methods in one click

Returns a list of variables, methods, and types defined in the current range without arguments; Returns a list of properties and methods for an argument.

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']
Copy the code

20 quotient and remainder

Take the quotient and remainder

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

21 Enumeration Object

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

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

22 Calculation expression

Evaluates the string STR as a valid expression and returns the result to fetch the contents of the string

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

23 Check the number of bytes in the variable

In [1]: import sys In [2]: a = {'a':1,'b':2.0} In [3]: sys. getSizeof (a) # Out[3]: 240Copy the code

24 filter

Set the filter condition in the function, iterating over the elements, keeping the elements that return True:

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

25 Convert to a floating point type

Converts an integer or numeric string to a floating point number

In [1]: float(3)
Out[1]: 3.0
Copy the code

If it cannot be converted to a floating point number, ValueError is raised:

In [2]: float('a') ValueError Traceback (most recent call last) <ipython-input-11-99859da4e72c> in <module>() ----> 1 float('a')  ValueError: could not convert string to float: 'a'Copy the code

26 String Formatting

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

In [104]: print("i am {0},age{1}".format("tom",18))
i am tom,age18
Copy the code
3.1415926 {:.2f} 3.14 Keep two decimal places
3.1415926 {:+.2f} + 3.14 The sign preserves two decimal places
– 1 {:+.2f} 1.00 The sign preserves two decimal places
2.71828 {:.0f} 3 With no decimal
5 {:0>2d} 05 Numeric zeroing (padding left, width 2)
5 {:x<4d} 5xxx Number fill x (fill right side, width 4)
10 {:x<4d} 10xx Number fill x (fill right side, width 4)
1000000 {:} 1000000 Number format separated by commas
0.25 } {: 2% 25.00% Percentage format
1000000000 {:.2e} 1.00 e+09 Index notation
18 {:>10d} ’18’ Right aligned (default, width 10)
18 {:<10d} ’18’ Left aligned (width 10)
18 {:^10d} ’18’ Middle alignment (width 10)

27 Frozen Set

Create a collection that cannot be modified.

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

Because they cannot be modified, there are no add and pop methods like set

28 Dynamically obtain object attributes

Gets 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]: Out[3]: 'xiaoming' getattr(xiaoming,'name') #Copy the code

29 Check 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')Copy the code

30 Returns the hash value of the object

Return the hash value of an object. Note that custom instances are hashable. Mutable objects such as lists, dict, and sets are unhashable.

In [1]: hash(xiaoming) Out[1]: 6139638 In [2]: Hash ([1,2,3]) TypeError Traceback (most recent call last) <ipython-input-32-fb5b1b1d9906> in <module>() ----> 1 Hash ([1,2,3]) TypeError: unhashable type: 'list'Copy the code

31 One-click Help

Returns the help document 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)
Copy the code

32 Object door number

Returns the memory address of the object

In [1]: id(xiaoming)
Out[1]: 98234208
Copy the code

33 Obtain user input

Gets user input

In [1]: input()
aa
Out[1]: 'aa'
Copy the code

34 is an integer

Int (x, base =10), x may be a string or number, converting x to a plain integer. If the argument is a string, it may contain symbols and decimal points. If the range of representations for ordinary integers is exceeded, a long integer is returned.

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

35 isinstance

Returns true if object is an instance of class ClassInfo

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]: TrueCopy the code

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]: TrueCopy the code

True is also returned if class is a subclass of an element in the ClassInfo tuple

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

37 Create an iterator type

Using iter(obj, sentinel), returns an iterable, sentinel can be omitted (terminates immediately once iterated to this element)

In [1] : LST =,3,5 [1] In [2] : for I the In iter (LST) :... : print(i) ... : 1 3 5Copy the code
In [1]: class TestIter(object): ... : def __init__(self): ... : the self l =,3,2,3,4,5 [1]... : self.i=iter(self.l) ... : def __call__ (self) : # define the instance of a class of __call__ method is callable... : item = next(self.i) ... : print ("__call__ is called,fowhich would return",item) ... : return item ... : def __iter__ (self) : # support iterative agreement (that is, the definition has __iter__ () function)... : print ("__iter__ is called!!" )... : return iter(self.l) In [2]: t = TestIter() In [3]: __call__ is called,which would return 1 Out[3]: 1 In [4]: for e In TestIter(): Because __iter__ is implemented, t can be iterated over... : print(e) ... : __iter__ is called!! One, three, two, three, four, fiveCopy the code

38 Root of all objects

Object is the base class of all classes

In [1]: o = object()

In [2]: type(o)
Out[2]: object
Copy the code

39 Opening the 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.'
Copy the code

Mode value table:

character meaning
'r' Read (default)
'w' Write, and truncate the file first
'x' Exclusive creation fails if the file already exists
'a' Write, appended to the end if the file exists
'b' Binary mode
't' Text mode (default)
'+' Open for update (read and write)

40 times the power

Base e to the power, mod if given

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

41 print

In [5] : LST =,3,5 [1] In [6] : print (LST) [1, 3, 5] In [7] : print (f 'LST: {LST}') LST: [1, 3, 5] In [8] : print('lst:{}'.format(lst)) lst:[1, 3, 5] In [9]: print('lst:',lst) lst: [1, 3, 5]Copy the code

42 Two ways to create attributes

Returns the property property. 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): X = property(getx, setx, delx, "I'm the 'x' property.")Copy the code

Use the Python decorator to achieve exactly the same effect 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
Copy the code

43 Create a range sequence

  1. range(stop)
  2. 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) Out[2]: range(0,11)Copy the code

44 Reverse iterator

In [1] : rev = reversed (,4,2,3,1 [1]) In [2] : for I In rev:... : print(i) ... : 1 3 2 4 1Copy the code

45 rounded

Rounding, ndigits indicates the number of digits to keep after the decimal point:

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

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

46 Change to the set type

Returns a set object in which no duplicate elements are allowed:

In [159] : a =,4,2,3,1 [1] In [160] : set Out (a) [160] : {1, 2, 3, 4}Copy the code

47 Convert the object into a slice

class slice(start, stop[, step])

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

In [1] : a =,4,2,3,1 [1] [2] : In my_slice_meaning = slice (0,5,2) In [3], a [my_slice_meaning] Out [3] : [1, 2, 1]Copy the code

48 just use the sorting function

Sorting:

In [1] : a =,4,2,3,1 [1] [2] : In sorted Out (a, reverse = True) [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'}]Copy the code

49 Summing function

Sum:

In [181]: a = [1,4,2,3,1] In [182]: sum(a) Out[182]: 11 In [185]: sum(a,10) # = 10 Out[185]: 21Copy the code

50 yuan group

Tuple () converts an object to an immutable sequence type

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

51 Check the object type

class type(name, bases, dict)

When passed a parameter, return the type of 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]: type(xiaoming) Out[3]: __main__.Student In [4]: type(tuple()) Out[4]: tupleCopy the code

52 Aggregate iterator

Create an iterator that aggregates elements from each iterable:

In [1] : x = (3, 2, 1] In [2] : y = (4 and 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']Copy the code

That’s the end of my sharing, and I hope you found it helpful

Thank you for your support!