Python作为我的主力语言帮助我开发了许多DevOps运维自动化系统,这篇文章总结几个我在编写Python代码过程中用到的几个简单又好用的特性和用法,这些特性和用法可以帮助我们更高效地编写Python代码
1.链式比较
- x = 5
- y = 10
- z = 15
-
- if x < y < z:
- print("x is less than y and y is less than z")
2.链式赋值
total_regions = region_total_instances = total_instances = 0
3.三元运算符
- x = 10
- result = "Greater than 10" if x > 10 else "Less than or equal to 10"
4.使用args和kwargs传递多个位置参数或关键字参数给函数
- def example_function(*args, **kwargs):
- for arg in args:
- # 执行相关操作
- for key, value in kwargs.items():
- # 执行相关操作
5.使用enumerate函数同时获取索引和值
- my_list = ['apple', 'banana', 'orange']
- for index, value in enumerate(my_list):
- print(f"Index: {index}, Value: {value}")
6.使用zip函数同时迭代多个可迭代对象
- list1 = [1, 2, 3]
- list2 = ['a', 'b', 'c']
- for item1, item2 in zip(list1, list2):
- print(f"Item from list1: {item1}, Item from list2: {item2}")
7.使用itertools模块进行迭代器和循环的高级操作
- import itertools
- for item in itertools.chain([1, 2, 3], ['a', 'b', 'c']):
- print(item)
8.使用collections.Counter进行计数
- from collections import Counter
- my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
- counter = Counter(my_list)
- print(counter) # 输出为Counter({'apple': 3, 'banana': 2, 'orange': 1})
9.使用any和all函数对可迭代对象中的元素进行逻辑判断
- my_list = [True, False, True, True]
- print(any(my_list)) # 输出为True
- print(all(my_list)) # 输出为False
10.使用sorted函数对可迭代对象进行排序
- my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
- sorted_list = sorted(my_list)
- print(sorted_list) # 输出为[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
11.使用set进行集合操作
- set1 = {1, 2, 3, 4, 5}
- set2 = {3, 4, 5, 6, 7}
- print(set1.union(set2)) # 输出为{1, 2, 3, 4, 5, 6, 7}
- print(set1.intersection(set2)) # 输出为{3, 4, 5}
12.上下文管理器
- class CustomContextManager:
- def __enter__(self):
- # 在代码块执行之前执行的操作
- # 可以返回一个值,该值将被赋值给as子句中的变量
-
- def __exit__(self, exc_type, exc_val, exc_tb):
- # 在代码块执行之后执行的操作
- # 可以处理异常,返回True表示异常被处理,False则会重新抛出异常
-
- # 使用自定义上下文管理器
- with CustomContextManager() as obj:
- # 在这里执行一些操作
13.生成器表达式
- # 使用生成器表达式计算1到10的平方和
- squared_sum = sum(x**2 for x in range(1, 11))
- print(squared_sum)
14.使用str.endswith()方法来检查字符串是否以元组中的任何一个字符串结尾
- filename = "example.csv"
- if filename.endswith((".csv", ".xls", ".xlsx")):
- # 执行相关操作
同样的用法还有str.startswith()来检查字符串是否以元组中的任何一个字符串开头
15.else语句与for和while循环结合使用
- for item in some_list:
- if condition:
- # 执行相关操作
- break
- else:
- # 如果循环自然结束,执行相关操作
16.静态类型检查
- # 使用mypy进行静态类型检查
- def add_numbers(a: int, b: int) -> int:
- return a + b
-
- result = add_numbers(5, 10)
- print(result)
先总结这么多,欢迎补充
文章转载自:ops-coffee