Python中那些简单又好用的特性和用法

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.使用argskwargs传递多个位置参数或关键字参数给函数

复制代码
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.使用anyall函数对可迭代对象中的元素进行逻辑判断

复制代码
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

原文链接: https://www.cnblogs.com/37Y37/p/18057101

体验地址: 引迈 - JNPF快速开发平台_低代码开发平台_零代码开发平台_流程设计器_表单引擎_工作流引擎_软件架构

相关推荐
老胖闲聊2 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1182 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之2 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
apocelipes2 小时前
Linux c 运行时获取动态库所在路径
linux·c语言·linux编程
努力学习的小廉3 小时前
深入了解linux系统—— 进程池
linux·运维·服务器
lyaihao3 小时前
使用python实现奔跑的线条效果
python·绘图
秃头菜狗3 小时前
各个主要目录的功能 / Linux 常见指令
linux·运维·服务器
2301_793102493 小时前
Linux——MySql数据库
linux·数据库
ai大师4 小时前
(附代码及图示)Multi-Query 多查询策略详解
python·langchain·中转api·apikey·中转apikey·免费apikey·claude4
vfvfb4 小时前
bat批量去掉本文件夹中的文件扩展名
服务器·windows·批处理·删除扩展名·bat技巧