Article | doug \
Source: Python Technology “ID: pythonall”
As we all know, Python is famous for its syntax brevity, and the same function can be implemented in a single line in Java, which may take a dozen lines.
Python code is so elegant because of its unique features that you can write poetic code if you master them.
Let’s take a look at the dirty operations in Python.
0x00 Hello World
For most programmers, the first program should be “Hello World!” Python directly makes the starter into a package.
In [1] :import __hello__
Hello world!
Copy the code
0x01 Swap variables
One line of code handles variable swaps, no temporary variables, no xor operations.
In [1]: x,y = y,x
Copy the code
0x02 Variable comparison
For continuous comparisons of variables, Python supports them well.
In [24]: x = 10
In [25] :5 < x < 20
Out[25]: True
In [26] :11 < x < 20
Out[26]: False
Copy the code
0x03 List derivation
In [2]: list = list(range(10) # In [3]: even = [x for x in list if x % 2= =0]
In [4]: even
Out[4] : [0.2.4.6.8]
Copy the code
0x04 Merge string
Many languages merge strings through the + sign, but because of the immutability of the string, the string will continue to apply for new memory.
In [5]: x = ['a'.'b'.'c'.'d'.'e'.'f'.'g']
In [6] :' '.join(x)
Out[6] :'abcdefg'
Copy the code
0x05 List slice
In [2]: x
Out[2] : [0.1.2.3.4.5.6.7.8.9Select * from index where id = 12 到 8, and the step size is2
In [4]: x[2:8:2]
Out[4] : [2.4.6# step In [6]: x[::2 -]
Out[6] : [9.7.5.3.1]
Copy the code
0x06 Reverse string
In [7]: x = 'Hello Python! '
In [8]: x[::- 1]
Out[8] :'! nohtyP olleH'
Copy the code
0x07 gets both the subscript and the value
x = list(range(10))
for index, value in enumerate(x):
print(index, value)
Copy the code
0 x08 zip () function
In [7]: a = [1.2.3]
In [8]: b = [4.5.6]
In [9]: c = [7.8.9]
In [16]: list(zip(a, b, c))
Out[16] : [(1.4.7), (2.5.8), (3.6.9) # # # # #18]: zz = (zip(a, b, c))
In [19]: x, y, z = zip(*zz)
In [20]: x,y,z
Out[20] : ((1.2.3), (4.5.6), (7.8.9) # merge list adjacent entries In [22]: a = [1.2.3.4.5.6]
In [23]: list(zip(a[::2], a[1: :2]))
Out[23] : [(1.2), (3.4), (5.6)]
Copy the code
0 x09 closures
Outer (x): def inner(y): def outer(x): def inner(y)returnThe return value of x + y # is a reference to the inner functionreturn inner
fun = outer(10)
print(fun(10)) # 30
print(fun(10)) # 40
print(fun(10)) # 50
Copy the code
conclusion
Today we learned some Python tricks that you need to work with. Did you get it?
PS: Reply “Python” within the public number to enter the Python novice learning exchange group, together with the 100-day plan! \
Old rules, brothers still remember, the lower right corner of the “watching” click, if you feel the content of the article is good, remember to share moments to let more people know!
[Code access ****]
Identify the qr code at the end of the article, reply: 200619