Common python Functions
Python built-in functions
Enumerate
>>> List (enumerate ('abc '))
[(0, 'A'), (1, 'B'), (2, 'C')]
The enumerate function can also receive the second parameter.
>>> List (enumerate ('abc', 1 ))
[(1, 'A'), (2, 'B'), (3, 'C')]
Simple Server
Do you want to quickly and conveniently share files in a directory?
# Python2 python-m SimpleHTTPServer # Python 3 python3-m http. server
This will start a server.
Evaluate a Python expression
We all know eval functions, but do we know literal_eval functions?
Import ast
My_list = ast. literal_eval (expr)
To replace the following operations:
Expr = [1, 2, 3]
My_list = eval (expr)
Object self-check
In Python, you can use the dir () function to check objects. As shown in the following example:
>>> Foo = [1, 2, 3, 4]
>>> Dir (foo)
['_ Add _', '_ class _', '_ ins INS __',
'_ Delattr _', '_ delitem _', '_ delslice __',...,
'Extend', 'index', 'insert', 'pop', 'delete ',
'Reverse', 'sort ']
Ternary Computation
Ternary operations are quick operations for if-else statements, also known as conditional operations. Here are a few examples for your reference. They can make your code more compact and more beautiful.
[On_true] if [expression] else [on_false]
X, y = 50, 25
Small = x if x <y else y