Station B|Official account: a graduate student who knows everything
Related Reading
These seven 100% performance-improving Python code performance skills must be known. I
have sorted out a few Python detail pits that 100% will step on to prevent cerebral thrombosis in advance.
I have sorted out ten 100% efficient Python programming skills to improve
Python-list, from basic to advanced usage summary, come in to check
and fill in
gaps Big summary, come in to check and fill in the gapsPython
-collection, from basic to advanced Big summary, come in to check for leaks and fill in the gaps.
These bad habits of Python programming, including mine, get rid of the
pits of Python variable types as soon as possible, and don’t step on
the list anymore Comprehensions, the best feature in Python? readability?
Isn't a tuple just an immutable list?
Subscribe to the column ===> Python
When reading the code, you can often see a lot of single-line operations, which are simple and concise. In this issue, we will take stock of some common usages.
It is worth mentioning that don't over-pursue brevity and lose readability, otherwise colleagues will easily **
1. for loop
Write the for loop on one line using a list comprehension
For example, to filter out values less than 250
mylist = [200, 300, 400, 500]
# 常规方法
result = []
for x in mylist:
if x > 250:
result.append(x)
print(result) # [300, 400, 500]
# 单行方法
result = [x for x in mylist if x > 250]
print(result) # [300, 400, 500]
2. while loop
This example will show two ways to implement a single-line While loop
#Method 1 Single Statement
while True: print(1) #infinite 1
#Method 2 Multiple Statements
x = 0
while x < 5: print(x); x= x + 1 # 0 1 2 3 4 5
3. if else statement
To write an if-else statement in one line, you can use the ternary operator
Here are 3 examples to give you a clear idea of how to use the ternary operator for a single-line if-else statement
#if Else In a single line.
#Example 1 if else
print("Yes") if 8 > 9 else print("No") # No
#Example 2 if elif else
E = 2
print("High") if E == 5 else print("数据STUDIO") if E == 2 else
print("Low") # Data STUDIO
#Example 3 only if
if 3 > 2: print("Exactly") # Exactly
4. Merge dictionaries
Here are two ways to merge dictionaries
# Merging dictionaries in one line
d1 = {
'A': 1, 'B': 2 }
d2 = {
'C': 3, 'D': 4 }
#Method1
d1.update(d2)
print(d1) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
#Method2
d3 = {
**d1, **d2}
print(d3) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
5. One-line functions
There are two ways to achieve defining a function in one line
In the first approach, use the same function definition as the ternary operator or the one-line loop approach
The second way is to use lambda to define the function
#Function in one line
#Method1
def fun(x): return True if x % 2 == 0 else False
print(fun(2)) # False
#Method2
fun = lambda x : x % 2 == 0
print(fun(2)) # True
print(fun(3)) # False
6. Recursion
This example shows how to use recursion in one line, using a single-line function definition and a single-line if-else
Find the Fibonacci sequence
# Single-line recursion
#Fibonaci Single-line recursion example
def Fib(x): return 1 if x in {
0, 1} else Fib(x-1) + Fib(x-2)
print(Fib(5)) # 8
print(Fib(15)) # 987
7. Exception handling
Use exception handling to handle Python runtime errors, and you can write try except statements in general
This can also be done using the exec() statement
# Exception handling in one line
#Original method
try:
print(x)
except:
print("Error")
#Single line way
exec('try:print(x) \nexcept:print("Error")') # Error
8. Convert list to dictionary
Use the enumerate() function to convert a list to a dictionary in one line
Pass the list to enumerate() and use dict() to convert the final output to dictionary format
# Dictionary in one line
mydict = ["John", "Peter", "Mathew", "Tom"]
mydict = dict(enumerate(mydict))
print(mydict) # {0: 'John', 1: 'Peter', 2: 'Mathew', 3: 'Tom'}
9. Multiple variable assignment
Python allows multiple variable assignments in one line, that is, unpacking
#Multiple variable assignments in one line.
#Single-line method
x = 5
y = 7
z = 10
print(x , y, z) # 5 7 10
#Single line way
a, b, c = 5, 7, 10
print(a, b, c) # 5 7 10
10. Swap values in a row
In many programming languages, a third variable named temp is always required to hold the exchanged value
Whereas in Python you can easily do
#Swap values in one line
#Single-line method
v1 = 100
v2 = 200
temp = v1
v1 = v2
v2 = temp
print(v1, v2) # 200 100
# One-line value swapping
v1, v2 = v2, v1
print(v1, v2) # 200 100
11. Sort
Sorting is a common problem in programming, and Python has many built-in methods to solve it
# Sort in one line
mylist = [32, 22, 11, 4, 6, 8, 12]
# Method1
mylist.sort()
print(mylist) # # [4, 6, 8, 11, 12, 22, 32]
print(sorted(mylist)) # [4, 6, 8, 11, 12, 22, 32]
12. class
lambdas and namedtuples
# One-line class
#Regular way
class Emp:
def __init__(self, name, age):
self.name = name
self.age = age
emp1 = Emp("a44", 22)
print(emp1.name, emp1.age) #
#Single line way
#Method 1 Lambda with Dynamic Attributes
Emp = lambda:None; Emp.name = "a44"; Emp.age = 22
print(Emp.name, Emp.age) #
#Method 2
from collections import namedtuple
Emp = namedtuple('Emp', ["name", "age"]) ("a44", 22)
print(Emp.name, Emp.age)
13. Semicolon
# One-line semicolon
# exsample 1
a = "Python"; b = "Programming"; c = "languages"; print(a, b, c)
# print
# Python Programming languages
14. map
#One line map function
print(list(map(lambda a: a + 2, [5, 6, 7, 8, 9, 10])))
# print
# [7, 8, 9, 10, 11, 12]
15. Delete list multiple content
Use the del method to delete multiple elements from a list
# Deleting the Mul elements from the first row of the list
mylist = [100, 200, 300, 400, 500]
del mylist[1::2]
print(mylist) # [100, 300, 500]