This article is participating in the Python Theme Month, check out the detailsActive link

1. Swap variables

Sometimes, when we want to exchange the values of two variables, a common approach is to create a temporary variable and use it to do the swap. Ex. :

Temp = a = b b = temp print(a) print(b)Copy the code

2. The if statement is inside the line

print "Hello" if True else "World"

>>> Hello
Copy the code

3. Use a dictionary to store selection operations

We can construct a dictionary to store expressions:

In [70]: stdacl = { ... : 'sum':lambda x,y : x + y, ... : 'subtract':lambda x,y : x - y ... :} [73] : In stdacl [' sum '] Out (9, 3) [73] : 12 [74] : In stdacl [' subtract] Out [74] (9, 3) : 6Copy the code

4. A single line of code calculates the factorial of any number

Python3 environment:

In [75]: import functools
 
In [76]: result = ( lambda k : functools.reduce(int.__mul__,range(1,k+1),1))(3) 
 
In [77]: result
Out[77]: 6
Copy the code

5, connection

This last approach is cool when binding objects of two different types.

nfc = ["Packers", "49ers"]

afc = ["Ravens", "Patriots"]

print nfc + afc

>>> [''Packers'', ''49ers'', ''Ravens'', ''Patriots'']

print str(1) + " world"

>>> 1 world

print `1` + " world"

>>> 1 world

print 1, "world"

>>> 1 world

print nfc, 1

>>> [''Packers'', ''49ers''] 1
Copy the code

6. Calculation skills

Print 2**5 >> 32 print.3/.1 >>> 2.9999999996 printCopy the code

7. Find the most frequent number in the list

In [82] : test =,2,3,4,2,2,3,1,4,4,4 [1] In [83] : print (Max (set (test), key = test. The count)) 4Copy the code

8. Reset recursive limits

Python limits recursion to 1000 times. We can reset this value:

import sys
 
x=1001
print(sys.getrecursionlimit())
 
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
 
#1-> 1000
#2-> 100
Copy the code

9. Switch two digits in place

Python provides an intuitive way to assign and exchange (variable values) in a single line of code. See the following example:

In [1]: x,y = 10 ,20 
 
In [2]: print(x,y)
10 20
 
In [3]: x, y = y, x 
 
In [4]: print(x,y)
20 10
Copy the code

10. Chain-like comparison operator

Aggregation of comparison operators is another technique that is sometimes handy:

In [5]: n = 10 
 
In [6]: result = 1 < n < 20 
 
In [7]: result 
Out[7]: True
 
In [8]: result = 1 > n <= 9 
 
In [9]: result 
Out[9]: False
Copy the code

Use slots to reduce memory overhead

Have you noticed that your Python application is taking up a lot of resources, especially memory? One trick is to use the Slots class variable to reduce memory overhead somewhat.

```python import sys class FileSystem(object): def __init__(self, files, folders, devices): self.files = files self.folders = folders self.devices = devices print(sys.getsizeof( FileSystem )) class FileSystem1(object): __slots__ = ['files', 'folders', 'devices'] def __init__(self, files, folders, devices): Self.files = files self.folders = folders self.devices = devices print(sys.getSizeof (FileSystem1)) #In Python 3.5 #1-> 1016 # 2 - > 888Copy the code

12. Use lambda to mimic output methods

In [89]: import sys In [90]: lprint = lambda *args: sys.stdout.write("".join(map(str,args))) In [91]: Lprint (" python ", "tips", 1000100 (1) the Out [91] : pythontips1000100118Copy the code

13. Build a dictionary from two related sequences

In [92] : t1 = (1, 2, 3) [93] : In t2 = (10, 30) [94] : In dict (t1, t2) (zip) Out [94] : {1:10, 2:20, 3:30}Copy the code

14. A single line of code searches for multiple prefixes to a string

In [95]: print("http://www.google.com".startswith(("http://", "https://")))
True
 
In [96]: print("http://www.google.co.uk".endswith((".com", ".co.uk")))
True
Copy the code

Implement a true switch-case statement in Python

The following code uses a dictionary to simulate the construction of a switch-case. In [104]: def xswitch(x): ... : return xswitch._system_dict.get(x, None) ... : In [105]: xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2} In [106]: print(xswitch('default')) None In [107]: print(xswitch('devices')) 2Copy the code

16. Multi-line string

The basic way is to use backslashes from the C language:

In [20]: multistr = " select * from multi_row \ ... : where row_id < 5" In [21]: multistr Out[21]: ' select * from multi_row where row_id < 5'Copy the code

Another trick is to use triple quotes

In [23]: multistr ="""select * from multi_row ... : where row_id < 5""" In [24]: multistr Out[24]: 'select * from multi_row \nwhere row_id < 5'Copy the code

The common problem with the above methods is the lack of proper indentation, and if we try to indent it we will insert Spaces into the string. So the final solution is to break the string into multiple lines and enclose the entire string in parentheses:

In [25]: multistr = ("select * from multi_row " ... : "where row_id < 5 " ... : "order by age") In [26]: multistr Out[26]: 'select * from multi_row where row_id < 5 order by age'Copy the code

17. Iterate on both lists simultaneously

nfc = ["Packers", "49ers"]

afc = ["Ravens", "Patriots"]

for teama, teamb in zip(nfc, afc):

print teama + " vs. " + teamb

>>> Packers vs. Ravens

>>> 49ers vs. Patriots
Copy the code

18. Store list elements in new variables

We can use a list to initialize multiple variables. When parsing a list, the number of variables should not exceed the number of elements in the list:

In [27]: testlist = [1,2,3]
 
In [28]: x,y,z = testlist
 
In [29]: print(x,y,z)
1 2 3
Copy the code

Four ways to flip a string/list

Flip the list itself

In [49]: testList = [1, 3, 5]
 
In [50]: testList.reverse()
 
In [51]: testList
Out[51]: [5, 3, 1]
Copy the code

Flip in a loop and iterate over the output

In [52]: for the element In reversed([1,3,5]):... : print(element) ... : 5 3 1Copy the code

A line of code flips the string

In [53]: "Test Python"[::-1]
Out[53]: 'nohtyP tseT'
Copy the code

Use slices to flip the list

[1, 3, 5] [: : 1]Copy the code

20. Numerical comparison

x = 2

if 3 > x > 1:

print x

>>> 2

if 1 < x > 0:

print x

>>> 2
Copy the code

Play with enumeration

Using an enumeration makes it easy to find the (current) index in a loop:

In [54]: testList= [10,20,30] In [55]: for I,value In enumerate(testList): : print(i,':',value) ... : 0:10 1:20 2:30Copy the code

Using enumerators in Python

We can define an enumerator in the following way:

In [56]: class Shapes: ... : Circle,Square,Triangle,Quadrangle = range(4) ... : In [57]: Shapes.Circle Out[57]: 0 In [58]: Shapes.Square Out[58]: 1 In [59]: Shapes.Triangle Out[59]: 2 In [60]: Shapes.Quadrangle Out[60]: 3Copy the code

Returns multiple values from a method

Not many programming languages support this feature, however methods in Python do return multiple values. See the following example to see how this works:

In [61]: def x(): ... : return 1, 2, 3, 4... : In [62]: a,b,c,d = x() In [63]: print(a,b,c,d) 1 2 3 4Copy the code

Print the file path of the imported module

If you want to know the absolute path to a module referenced in your code, use the following technique:

In [30]: import threading In [31]: import socket In [32]: Print (threading) < module 'when' from '/ usr/local/lib/python3.5 / threading py' > In [33] : Print (socket) < module 'socket' from '/ usr/local/lib/python3.5 / socket. Py' >Copy the code

Iterated lists with indexes

teams = ["Packers", "49ers", "Ravens", "Patriots"]

for index, team in enumerate(teams):

print index, team

>>> 0 Packers

>>> 1 49ers

>>> 2 Ravens

>>> 3 Patriots
Copy the code

26. List derivation

Given a list, brush to select an even list:

Numbers = [1,2,3,4,5,6] even = [] for number in numbers: if number%2 == 0: even.append(number)Copy the code

27. Use the following instead

Numbers = [1,2,3,4,5,6] even = [number for number in numbers if number%2 == 0]Copy the code

28. Dictionary derivation

teams = ["Packers", "49ers", "Ravens", "Patriots"]

print {key: value for value, key in enumerate(teams)}

>>> {''49ers'': 1, ''Ravens'': 2, ''Patriots'': 3, ''Packers'': 0}
Copy the code

29. Initialize the list of values

Items = [0]*3 print items >>> [0,0,0]Copy the code

30. Convert the list to a string

teams = ["Packers", "49ers", "Ravens", "Patriots"]

print ", ".join(teams)

>>> ''Packers, 49ers, Ravens, Patriots''
Copy the code

31, get the element from the dictionary

Don’t do it in the following way

data = {''user'': 1, ''name'': ''Max'', ''three'': 4}

try:

is_admin = data[''admin'']

except KeyError:

is_admin = False
Copy the code

Replace with

data = {''user'': 1, ''name'': ''Max'', ''three'': 4}

is_admin = data.get(''admin'', False)
Copy the code

32, get the sublist

X = [6] [3] : # 3 print before x > > > [1, 2, 3] # 4 middle print x [1] > > > 5-tetrafluorobenzoic [2] # 3 print last x [- 3:] > > > (4 and 6) # odd term Print x [2] : : > > >,3,5 [1] # even term print x [1:2] > > > minus [2]Copy the code

Solve FizzBuzz in 60 characters

A while back Jeff Atwood popularized a simple programming exercise called FizzBuzz. The question is quoted as follows:

Write a program that prints numbers 1 to 100, replaces the number with “Fizz” for multiples of 3, “Buzz” for multiples of 5, and “FizzBuzz” for numbers that are both multiples of 3 and 5.

Here’s a short solution to this problem:

for x in range(101):print”fizz”[x%34::]+”buzz”[x%54::]or x

34, collections,

Library use Counter

from collections import Counter

print Counter("hello")

>>> Counter({''l'': 2, ''h'': 1, ''e'': 1, ''o'': 1})
Copy the code

35. Iterative tools

As with the Collections library, there is also a library called Itertools

from itertools import combinations

teams = [“Packers”, “49ers”, “Ravens”, “Patriots”]

for game in combinations(teams, 2):

print game

>>> (''Packers'', ''49ers'')

>>> (''Packers'', ''Ravens'')

>>> (''Packers'', ''Patriots'')

>>> (''49ers'', ''Ravens'')

>>> (''49ers'', ''Patriots'')

>>> (''Ravens'', ''Patriots'')
Copy the code

In Python, True and False are global variables, so:

False = True

if False:

print "Hello"

else:

print "World"

>>> Hello
Copy the code

36. The “_” operator in an interactive environment

This is a useful feature that most of us don’t know about. In the Python console, whenever we test an expression or call a method, the result is assigned to a temporary variable: _ (an underscore).

In [34]: 2 + 3
Out[34]: 5
 
In [35]: _
Out[35]: 5
 
In [36]: print(_)
5
Copy the code

The “_” is the output of the last expression executed.

37. Dictionary/set derivation

Similar to the list derivation we used, we can also use dictionary/set derivation. They are simple and effective to use. Here is an example:

In [37]: testDict = {i : i*i for i in range(5)}
 
In [38]: testSet = { i*2 for i in range(5)}
 
In [39]: testDict
Out[39]: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
 
In [40]: testSet
Out[40]: {0, 2, 4, 6, 8}
Copy the code

Note: There is only one <:> difference between the two statements. In addition, when running the above code in Python3, it will be changed.

Debug script

We can set breakpoints in a Python script with the help of a module. Here is an example:

import pdb
pdb.set_trace()
Copy the code

It’s easy to specify <pdb.set_trace()> anywhere in the script and set a breakpoint there.

39. Start file sharing

Python allows you to run an HTTP server to share files from the root path. Here are the commands to start the server :(python3 environment)

python3 -m http.server
Copy the code

The above command will start a server on the default port 8000. You can pass a custom port number as the last parameter to the above command.

Paste_Image.png
Copy the code

40. Simplify if statements

We can verify multiple values using the following method:

If m in hc-positie [1] :Copy the code

Rather than

if m==1 or m==3 or m==5 or m==7:
Copy the code

Alternatively, we can use ‘{1,3,5,7}’ instead of ‘[1,3,5,7]’ for the in operator, because taking elements in set is an O(1) operation. 27. The runtime detects the Python version

Sometimes we may not want to run our programs when we are running a lower version of Python than the supported version. To do this, you can use the following code snippet, which also outputs the current Python version in a readable way:

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.5n") print("Please upgrade to 3.5.n") sys.exit(1) # print Python version in a readable format. print("Current Python version: ", sys.version)Copy the code

Or you can use sys.version_info >= (3, 5) to replace sys.hexversion! = 50660080, this is a reader’s suggestion.

Python3 run result:

Python 3.5.1 (Default, Dec 2015, 13:05:11) [GCC 4.8.2] Linux Current Python version: 3.5.2 (Default, Aug 22 2016, 21:11:05) [GCC 5.3.0]Copy the code

41. Combine multiple strings

If you want to concatenate all the tokens in a list, as in the following example:

In [44]: test = ['I', 'Like', 'Python', 'automation']
 
In [45]: ''.join(test)
Out[45]: 'ILikePythonautomation'
Copy the code

42. Construct a list without using a loop

In [101]: test = [[-1, -2], [30, 40], [25, 35]]
 
In [102]: import itertools
 
In [103]: print(list(itertools.chain.from_iterable(test)))
[-1, -2, 30, 40, 25, 35]
Copy the code

Exchange two numbers in place

x, y =10, 20
print(x, y)
y, x = x, y
print(x, y)
Copy the code

10 to 20

20 and 10

44. Chain comparison operator

n = 10
print(1 < n < 20)
print(1 > n <= 9)
Copy the code

True

False

45. Use ternary operators for conditional assignment

[return value if expression is true] if [expression] else [return value if expression is false]

y = 20
x = 9 if (y == 10) else 8
print(x)
Copy the code

Find the smallest number in ABC

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

X = [m**2 if m>10 else m**4 for m in range(50)] print(x)Copy the code

[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, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

​​

46, multi-line string

multistr = "select * from multi_row \
where row_id < 5"
print(multistr)
select * from multi_row where row_id < 5
multistr = """select * from multi_row
where row_id < 5"""
print(multistr)
select * from multi_row
where row_id < 5
multistr = ("select * from multi_row"
"where row_id < 5"
"order by age")
print(multistr)
select * from multi_rowwhere row_id < 5order by age
Copy the code

47. Store list elements in new variables

Print (x, y, z) print(x, y, z)Copy the code

1 2 3

Print the absolute path of the imported module

import threading
import socket
print(threading)
print(socket)
<module 'threading' from 'd:\\python351\\lib\\threading.py'>
<module 'socket' from 'd:\\python351\\lib\\socket.py'>
Copy the code

49. The “_” operator in an interactive environment

In the Python console, whenever we test an expression or call a method, the result is assigned to a temporary variable “_”

50. Dictionary/set derivation

testDic = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDic)
print(testSet)
Copy the code

{0:0, 1, 1, 2, 4, 3, 9, 4:16, 5:25, 6:36, 7:49, 8, 64, 9:81}

{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}

Debug script

Set breakpoints with the PDB module

import pdb
pdb.ste_trace()
Copy the code

52. Start file sharing

Python allows you to enable an HTTP server to share files from the root directory

python -m http.server
Copy the code

53. Simplify the if statement

# use following way to verify multi values
if m in [1, 2, 3, 4]:
# do not use following way
if m==1 or m==2 or m==3 or m==4:
Copy the code

54. Combine multiple strings

test = ["I", "Like", "Python"]
print(test)
print("".join(test))
Copy the code

[‘I’, ‘Like’, ‘Python’]

ILikePython

Use enumeration to find the index in the loop

test = [10, 20, 30]
for i, value in enumerate(test):
    print(i, ':', value)
Copy the code

Zero: 10

1:20

2:30

56, Define enumerators

class shapes:
    circle, square, triangle, quadrangle = range(4)
print(shapes.circle)
print(shapes.square)
print(shapes.triangle)
print(shapes.quadrangle)
Copy the code

Return multiple values from a method

def x():
    return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
Copy the code

1 2 3 4

58, use * operator unpack function arguments

def test(x, y, z):
    print(x, y, z)
testDic = {'x':1, 'y':2, 'z':3}
testList = [10, 20, 30]
test(*testDic)
test(**testDic)
test(*testList)
Copy the code

z x y

1 2 3

10 to 20 30

59. Use a dictionary to store expressions

stdcalc = {
    "sum": lambda x, y: x + y,
    "subtract": lambda x, y: x - y
}
print(stdcalc["sum"](9, 3))
print(stdcalc["subtract"](9, 3))
Copy the code

12

6

60, Calculate the factorial of any number

import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)
Copy the code

61, Find the number of times in the list

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 4]
print(max(set(test), key=test.count))
4
Copy the code

Reset the recursive limit

Python limits recursion to 1000, which can be reset using the following method

import sys
x = 1200
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
Copy the code

Check the memory usage of an object

Import sys x = 1 print(sys.getSizeof (x)) # Python3.5 a 32-bit integer takes 28 bytesCopy the code

Use slots to reduce memory overhead

Import sys class FileSystem(object): def __init__(self, files, folders, devices): Folders = folders self.devices = Devices print(sys.getSizeof (FileSystem) FileSystem(object): __slots__ = ['files', 'folders', 'devices'] def __init__(self, files, folders, devices): self.files = files self.folder = folders self.devices = devices print(sys.getsizeof(FileSystem))Copy the code

Use lambda to mimic output methods

import sys
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))
lprint("python", "tips", 1000, 1001)
Copy the code

66. Build a dictionary from two related sequences

t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))
Copy the code

{1:10, 2:20, 3:30}

Search for multiple prefixes to a string

print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))
Copy the code

68. Construct a list without using a loop

import itertools
import numpy as np
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
Copy the code

[-1, -2, 30, 40, 25, 35]

Implement the switch-case statement

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

I am white and white I, a love to share knowledge of the program yuan ❤️

If you have no contact with the programming section of the friends see this blog, find do not understand or want to learn Python, you can directly leave a message + private I ducky [thank you very much for your likes, collection, attention, comments, one button four connect support]