Have you mastered these 30 Python basic codes?

1 Find the absolute value

absolute value or modulo of a complex number

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

2 elements are both true

Accepts an iterator, 所有元素returns if all of the iterators are true, Trueotherwise returnsFalse

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

3 elements at least one is true 

Accepts an iterator, 至少有一个returns if the element in the iterator is true, Trueotherwise returnsFalse

In [4]: any([0,0,0,[]])Out[4]: False In [5]: any([0,0,1])Out[5]: True

4 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

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

5 ten to two

will 十进制convert to二进制

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

6 ten to eight

will 十进制convert to八进制

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

7 ten to sixteen

will 十进制convert to十六进制


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

​​​​​

Judgment is true or false  

Tests whether an object is True or False.

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

9 String to byte  

converts one 字符串into 字节the type

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

10 converted to string  

Convert 字符类型, , 数值类型etc. to 字符串types

​​​​​​​

In [1]: i = 100 In [2]: str(i)Out[2]: '100'

 11. Is it callable  

Determine whether the object can be called. The object that can be called is an callable object, such as a function  strint etc., which can be called, but xiaomingthe instance in Example 4 cannot be called:

​​​​​​​

In [1]: callable(str)Out[1]: True In [2]: callable(int)Out[2]: True In [3]: xiaomingOut[3]: id = 001, name = xiaoming In [4]: callable(xiaoming)Out[4]: False

If you want xiaomingto be able to call xiaoming(), you need to override the method Studentof the class __call__:

​​​​​​​

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 calledmy name is xiaoming

12 ten turn ASCII

View the corresponding decimal integerASCII字符

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

13 ASCII turn ten

View a ASCII字符corresponding decimal number

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

14 Static methods 

classmethod The function corresponding to the decorator does not need to be instantiated and does not need  selfparameters, but the first parameter needs to be the cls parameter representing its own class, which can be used to call the properties of the class, the method of the class, the instantiated object, 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)

15 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]: rOut[3]: <code object <module> at 0x0000000005DE75D0, file "<string>", line 1>    In [4]: exec(r)helloworld

16 Create complex numbers

create a plural

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

17 Dynamically delete attributes  

delete object properties

​​​​​​​

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

18. 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}

19 View all methods of an object with one click 

当前范围Returns a list of variables, methods, and defined types when there are no parameters ; returns 参数a list of attributes and methods when there are parameters.


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']

20 Take quotient and remainder  

Take the quotient and remainder separately

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

21 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 a2 b3 c

22 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

23.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

24 filters  

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

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

25.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 into a floating point number, it will report ValueError:

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'

26 String Formatting 

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

In [104]: print("i am {0},age{1}".format("tom",18))i am tom,age18
3.1415926 {:.2f} 3.14 Keep two decimal places
3.1415926 {:+2f} +3.14 Signed to two decimal places
-1 {:+2f} -1.00 Signed to two decimal places
2.71828 {:.0f} 3 without decimals
5 {:0>2d} 05 Numeric zero padding (padding to the left, width is 2)
5 {:x<4d} 5xxx Number complement x (fill right, width is 4)
10 {:x<4d} 10xx Number complement x (fill right, width is 4)
1000000 {:,} 1,000,000 comma-separated number format
0.25 {:.2%} 25.00% percentage form
1000000000 {:.2e} 1.00e+09 Exponential notation
18 {:>10d} ‘18’ Align right (default, width 10)
18 {:<10d} ‘18’ Align left (width 10)
18

{:^10d}

‘18’

Center aligned (width 10)

 

 27 Freeze Collection  

Create an unmodifiable collection.

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

Since it is not modifiable, there is no sum method like setthataddpop

28 Get 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'

29 Does the object have 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')

30 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 variable objects such as , listdictand  setso on are all unhashable (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'

Guess you like

Origin blog.csdn.net/CSDN6706/article/details/130481180