Home > Article > Backend Development > Summarize thirty practical skills of Python
This article brings you relevant knowledge about python, which mainly summarizes some common usage techniques in the programming process, including checking objects, using multi-line strings, and following functions Returning multiple values and other related content, I hope it will be helpful to everyone.
Recommended learning: python tutorial
Python provides a An intuitive way to perform assignments and exchanges in one line. Please refer to the example below.
x, y = 10, 20print(x, y) x, y = y, xprint(x, y) #1 (10, 20)#2 (20, 10)
The assignment on the right seeds a new tuple. And the left one immediately unpacks that (unquoted) tuple into the names <a>
and <b>
.
After allocation is complete, the new tuple will be dereferenced and marked for garbage collection. The exchange of variables also occurs at the end.
Aggregation of comparison operators is another trick that sometimes comes in handy.
n = 10 result = 1 < n < 20 print(result) # True result = 1 > n <= 9 print(result) # False
The ternary operator is a shortcut for if-else statements, also known as conditional operators.
[on_true] if [expression] else [on_false]
Here are some examples you can use to make your code compact and concise.
The following statement has the same meaning as "if y is 9, then assign 10 to x, otherwise assign 20 to x". We can extend the chaining of operators if needed.
x = 10 if (y == 9) else 20
Similarly, we can do the same thing with class objects.
x = (classA if y == 1 else classB)(param1, param2)
In the above example, classA and classB are two classes, one of which class constructor will be called.
The following is an example of no. Add a condition that evaluates the smallest number.
def small(a, b, c): return a if a <= b and a <= c else (b if b <= a and b <= c else c) print(small(1, 0, 1))print(small(1, 2, 2))print(small(2, 2, 3))print(small(5, 4, 3))#Output#0 #1 #2 #3
We can even use the ternary operator in list comprehensions.
[m**2 if m > 10 else m**4 for m in range(50)]#=> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
The basic method is to use backslashes derived from the C language.
multiStr = "select * from multi_row \ where row_id < 5"print(multiStr)# select * from multi_row where row_id < 5
Another tip is to use triple quotes.
multiStr = """select * from multi_row where row_id < 5"""print(multiStr)#select * from multi_row #where row_id < 5
A common problem with the above methods is the lack of proper indentation. If we try to indent, it inserts spaces in the string.
So the final solution is to split the string into multiple lines and enclose the whole string in brackets.
multiStr= ("select * from multi_row ""where row_id < 5 ""order by age") print(multiStr)#select * from multi_row where row_id < 5 order by age
We can use a list to initialize a no. Variables. When unpacking a list, the number of variables should not exceed the number. elements in the list.
testList = [1,2,3]x, y, z = testListprint(x, y, z)#-> 1 2 3
If you want to know the absolute location of the imported module in your code, use the following tip.
import threading import socketprint(threading)print(socket)#1- <module 'threading' from '/usr/lib/python2.7/threading.py'>#2- <module 'socket' from '/usr/lib/python2.7/socket.py'>
This is a useful feature that many of us don’t know about.
In the Python console, whenever we test an expression or call a function, the results are sent to the temporary name _ (underscore).
>>> 2 + 13>>> _3>>> print _3
"_" refers to the output of the last executed expression.
Just like we use list comprehensions, we can also use dictionary/set comprehensions. They are easy to use and equally effective. Here is an example.
testDict = {i: i * i for i in xrange(10)} testSet = {i * 2 for i in xrange(10)}print(testSet)print(testDict) #set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18]) #{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
Note - The only difference between the two statements is <:>. Also, to run the above code in Python3, replace with .
We can set breakpoints in Python scripts with the help of the module. Please follow the example below.
import pdb pdb.set_trace()
We can specify
Python allows running an HTTP server, which you can use to share files from the server root. Below is the command to start the server.
python -m SimpleHTTPServer
python3 -m http.server
The above command will start the server on the default port 8000. You can also use a custom port by passing it as the last parameter to the above command.
We can check objects in Python by calling the dir() method. This is a simple example.
test = [1, 3, 5, 7]print( dir(test) )
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
To validate multiple values, we can do it in the following way.
if m in [1,3,5,7]:
Instead of:
if m==1 or m==3 or m==5 or m==7:
Alternatively, we can use '{1,3,5,7}' instead of '[1,3,5,7]' as the 'in' operation symbol because 'set' can access each element in O(1).
Sometimes, we may not want to execute our program if the Python engine currently running is lower than the supported version. To do this, you can use the following code snippet. It also prints the currently used Python version in a human-readable format.
import sys#Detect the Python version currently in use.if not hasattr(sys, "hexversion") or sys.hexversion != 50660080: print("Sorry, you aren't running on Python 3.5\n") print("Please upgrade to 3.5.\n") sys.exit(1) #Print Python version in a readable format.print("Current Python version: ", sys.version)
Alternatively, you can replace sys.hexversion!= 50660080 with sys.version_info >= (3, 5) in the above code. This is the advice of an informed reader.
Output when running on Python 2.7.
Python 2.7.10 (default, Jul 14 2015, 19:46:27)[GCC 4.8.2] on linux Sorry, you aren't running on Python 3.5Please upgrade to 3.5.
在 Python 3.5 上运行时的输出。
Python 3.5.1 (default, Dec 2015, 13:05:11)[GCC 4.8.2] on linux Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05) [GCC 5.3.0]
如果您想连接列表中所有可用的标记,请参见以下示例。
>>> test = ['I', 'Like', 'Python', 'automation']
现在,让我们从上面给出的列表中的元素创建一个字符串。
>>> print ''.join(test)
testList = [1, 3, 5]testList.reverse()print(testList)#-> [5, 3, 1]
for element in reversed([1,3,5]): print(element)#1-> 5#2-> 3#3-> 1
"Test Python"[::-1]
这使输出为“nohtyP tseT”
[1, 3, 5][::-1]
上面的命令将输出 [5, 3, 1]。
使用枚举器,在循环中很容易找到索引。
testlist = [10, 20, 30]for i, value in enumerate(testlist): print(i, ': ', value)#1-> 0 : 10#2-> 1 : 20#3-> 2 : 30
我们可以使用以下方法来创建枚举定义。
class Shapes: Circle, Square, Triangle, Quadrangle = range(4)print(Shapes.Circle)print(Shapes.Square)print(Shapes.Triangle)print(Shapes.Quadrangle)#1-> 0#2-> 1#3-> 2#4-> 3
支持此功能的编程语言并不多。但是,Python 中的函数确实会返回多个值。
请参考以下示例以查看它的工作情况。
# function returning multiple values.def x(): return 1, 2, 3, 4# Calling the above function.a, b, c, d = x()print(a, b, c, d)
#-> 1 2 3 4
splat 运算符提供了一种解压参数列表的艺术方式。为清楚起见,请参阅以下示例。
def test(x, y, z): print(x, y, z)testDict = {'x': 1, 'y': 2, 'z': 3} testList = [10, 20, 30]test(*testDict)test(**testDict)test(*testList)#1-> x y z#2-> 1 2 3#3-> 10 20 30
我们可以制作一个字典存储表达式。
stdcalc = { 'sum': lambda x, y: x + y, 'subtract': lambda x, y: x - y}print(stdcalc['sum'](9,3))print(stdcalc['subtract'](9,3))#1-> 12#2-> 6
result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)print(result)#-> 6
import functools result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)print(result)
#-> 6
test = [1,2,3,4,2,2,3,1,4,4,4]print(max(set(test), key=test.count))#-> 4
Python 将递归限制限制为 1000。我们可以重置它的值。
import sys x=1001print(sys.getrecursionlimit())sys.setrecursionlimit(x)print(sys.getrecursionlimit())#1-> 1000#2-> 1001
请仅在需要时应用上述技巧。
在 Python 2.7 中,32 位整数消耗 24 字节,而在 Python 3.5 中使用 28 字节。为了验证内存使用情况,我们可以调用 方法。
import sys x=1print(sys.getsizeof(x))#-> 24
import sys x=1print(sys.getsizeof(x))#-> 28
你有没有观察到你的 Python 应用程序消耗了大量资源,尤其是内存?这是使用<__slots__>
类变量在一定程度上减少内存开销的一种技巧。
import sysclass FileSystem(object): def __init__(self, files, folders, devices): self.files = files self.folders = folders self.devices = devicesprint(sys.getsizeof( FileSystem ))class FileSystem1(object): __slots__ = ['files', 'folders', 'devices'] def __init__(self, files, folders, devices): self.files = files self.folders = folders self.devices = devicesprint(sys.getsizeof( FileSystem1 ))#In Python 3.5#1-> 1016#2-> 888
显然,您可以从结果中看到内存使用量有所节省。但是当一个类的内存开销不必要地大时,你应该使用 __slots__
。仅在分析应用程序后执行此操作。否则,您将使代码难以更改并且没有真正的好处。
import sys lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))lprint("python", "tips",1000,1001)#-> python tips 1000 1001
t1 = (1, 2, 3)t2 = (10, 20, 30)print(dict (zip(t1,t2)))#-> {1: 10, 2: 20, 3: 30}
print("http://www.baidu.com".startswith(("http://", "https://")))print("https://juejin.cn".endswith((".com", ".cn")))#1-> True#2-> True
import itertools test = [[-1, -2], [30, 40], [25, 35]]print(list(itertools.chain.from_iterable(test)))#-> [-1, -2, 30, 40, 25, 35]
如果您有一个包含嵌套列表或元组作为元素的输入列表,请使用以下技巧。但是,这里的限制是它使用了 for 循环。
def unifylist(l_input, l_target): for it in l_input: if isinstance(it, list): unifylist(it, l_target) elif isinstance(it, tuple): unifylist(list(it), l_target) else: l_target.append(it) return l_target test = [[-1, -2], [1,2,3, [4,(5,[6,7])]], (30, 40), [25, 35]]print(unifylist(test,[]))#Output => [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
统一包含列表和元组的列表的另一种更简单的方法是使用 Python 的 < more_itertools > 包。它不需要循环。只需执行 < pip install more_itertools >,如果还没有的话。
import more_itertools test = [[-1, -2], [1, 2, 3, [4, (5, [6, 7])]], (30, 40), [25, 35]]print(list(more_itertools.collapse(test)))#Output=> [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
这是使用字典来模仿 switch-case 构造的代码。
def xswitch(x): return xswitch._system_dict.get(x, None) xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2}print(xswitch('default'))print(xswitch('devices'))#1-> None#2-> 2
推荐学习:python学习教程
The above is the detailed content of Summarize thirty practical skills of Python. For more information, please follow other related articles on the PHP Chinese website!