introduce
Python is a versatile programming language with tons of libraries and frameworks. There are some lesser-known Python coding tricks and libraries that can make your job as a developer easier and your code more efficient.
In this article, I'll explore some lesser-known Python tricks that are useful but not widely known. By learning and using these techniques, you can save time and effort, and make your code more elegant and efficient. So, let's dig into these hidden treasures of the Python language!
1. Ternary operator
The ternary operator is shorthand for an if-else statement. the syntax is
value_if_true if condition else value_if_false
The ternary operator is a one-liner that can replace multi-line if-else statements, making your code more concise.
a = 5
b = 10
max = a if a > b else b # value_if_true if condition else value_if_false
print(max)
# 10
The above code works by checking if "a" is greater than "b" and returns "a" if true and "b" if false .
2. Enumeration function
The enumerate() function adds a counter to an iterable object and returns it as an enumeration object. This function is useful when you want to iterate over a list and keep track of the index.
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
print(index, fruit)
# 0 apple
# 1 banana
#2 mango
3. Compression function
The zip() function aggregates the elements from each iterable and returns a tuple iterator. This function is useful when you want to iterate over two or more lists at the same time.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for x, y in zip(list1, list2):
print(x, y)
# 1 a
# 2 b
# 3 c
4. List generation
List comprehensions are a concise way to create a list from an existing list or any iterable object. This is a one-liner that can replace for loops, making your code more efficient and making your code more readable.
squared_numbers = [x**2 for x in range(1, 6)]
print(squared_numbers)
# [1, 4, 9, 16, 25]
5. Anonymous functions
Lambda functions are anonymous functions defined using the lambda keyword. They are useful when you need to write small one-off functions and don't want to use the keyword def to define named functions.
add = lambda x, y: x + y
result = add(3, 4)
print(result)
# 7
6. any() and all() functions
The any() function and all() function return True or False based on the authenticity of the elements in the iterable . The function any() returns True if any element in the iterable is true and the function all() returns True if all the elements in the iterable are true .
numbers = [1, 2, 3, 0, 4]
result = any(numbers) # True
result = all(numbers) # False。0使结果为False
7. Iteration module
The itertools module provides a set of functions to work with iterators. Functions in this module include chain , product and permutations .
import itertools
numbers = [1, 2, 3]
result = list(itertools.permutations(numbers))
# 输出所有排列组合
# [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
8. Generator
A generator is an iterable type that yields values on the fly instead of storing them in memory. It is defined using the yield keyword and is used to create custom iterators.
# 使用yield关键字创建生成器
def fibonacci_series(n):
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b
# 输出迭代器中的值
for number in fibonacci_series(10):
print(number)
# 0
# 1
# 1
# 2
# 3
# 5
# 8
# 13
# 21
# 34
9. Decorator
A decorator is a way to modify the behavior of a function or class. Defined using the @ symbol, which can be used to add functionality to a function, such as logging, timing, or authentication.
def log_function(func):
def wrapper(*args, **kwargs):
print(f'Running {func.__name__}')
result = func(*args, **kwargs)
print(f'{func.__name__} returned {result}')
return result
return wrapper
@log_function
def add(x, y):
return x + y
print(add(5,7))
# 运行add函数,返回值为12
10. Use multiple function parameters
In Python , you can use the * and ** operators to handle multiple function arguments. The * operator is used to pass a list of arguments as individual positional arguments, and the operator ** is used to pass a dictionary of keyword arguments.
def print_arguments(*args, **kwargs):
print(args)
print(kwargs)
print_arguments(1, 2, 3, name='John', age=30)
# (1, 2, 3)
# {'name': 'John', 'age': 30}
11. Dynamic import
Modules can be dynamically imported using importlib when you want to import modules based on user input or configuration .
import importlib
module_name = 'math'
module = importlib.import_module(module_name)
result = module.sqrt(9)
12. Dictionary generation
Dictionary comprehensions are a concise way to create a dictionary from an existing dictionary or any iterable object. It is a one-liner that can replace the for loop, making your code more efficient and more readable.
squared_numbers = {x: x**2 for x in range(1, 6)}
print(squared_numbers)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
13. Callable objects
In Python , any object that can be called a function is called a callable object, including functions, methods, classes, and even objects that define a __call__ method.
class Adder:
def __call__(self, x, y):
return x + y
adder = Adder()
result = adder(3, 4)
print(result)
#7
14. Separate large numbers / characters with underscores
Large numbers are difficult to see at a glance, and underscores can be used in Python to make numbers more readable.
num_test = 100_345_405 # 一个大数字
print(num_test)
# 100345405
15. Quickly merge two dictionaries
You can quickly merge 2 two dictionaries in Python using the following code .
dictionary_one = {"a": 1, "b": 2}
dictionary_two = {"c": 3, "d": 4}
merged = {**dictionary_one, **dictionary_two}
print(merged)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}
16. Lists, sets, and dictionaries are mutable
Mutable means that the object (list, collection, or dictionary) can be changed or updated without changing the object's pointer in memory. The actual effect can be seen in the following example.
In the example below, which updates the list of cities by adding a new city, you can see that the ID (object pointer) remains the same, as do the collections and dictionaries.
cities = ["Munich", "Zurich", "London"]
print(id(cities)) # 2797174365184
cities.append("Berlin")
print(id(cities)) # 2797174365184
# 集合
my_set = {1, 2, 3}
print(id(my_set)) # 2797172976992
my_set.add(4)
print(id(my_set)) # 2797172976992
# 字典
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(id(thisdict)) #2797174128256
thisdict["engine"] = "2500cc"
print(id(thisdict)) #2797174128256
< END >
Well, that's all for today's sharing. If it is helpful to you, you can help to like, follow and repost. Thank you very much for your support! !