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


    Python作为我的主力语言帮助我开发了许多DevOps运维自动化系统,这篇文章总结几个我在编写Python代码过程中用到的几个简单又好用的特性和用法,这些特性和用法可以帮助我们更高效地编写Python代码

    1.链式比较

    1. x = 5
    2. y = 10
    3. z = 15
    4. if x < y < z:
    5. print("x is less than y and y is less than z")

    2.链式赋值

    total_regions = region_total_instances = total_instances = 0

    3.三元运算符

    1. x = 10
    2. result = "Greater than 10" if x > 10 else "Less than or equal to 10"

    4.使用argskwargs传递多个位置参数或关键字参数给函数

    1. def example_function(*args, **kwargs):
    2. for arg in args:
    3. # 执行相关操作
    4. for key, value in kwargs.items():
    5. # 执行相关操作

    5.使用enumerate函数同时获取索引和值

    1. my_list = ['apple', 'banana', 'orange']
    2. for index, value in enumerate(my_list):
    3. print(f"Index: {index}, Value: {value}")

    6.使用zip函数同时迭代多个可迭代对象

    1. list1 = [1, 2, 3]
    2. list2 = ['a', 'b', 'c']
    3. for item1, item2 in zip(list1, list2):
    4. print(f"Item from list1: {item1}, Item from list2: {item2}")

    7.使用itertools模块进行迭代器和循环的高级操作

    1. import itertools
    2. for item in itertools.chain([1, 2, 3], ['a', 'b', 'c']):
    3. print(item)

    8.使用collections.Counter进行计数

    1. from collections import Counter
    2. my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
    3. counter = Counter(my_list)
    4. print(counter) # 输出为Counter({'apple': 3, 'banana': 2, 'orange': 1})

    9.使用anyall函数对可迭代对象中的元素进行逻辑判断

    1. my_list = [True, False, True, True]
    2. print(any(my_list)) # 输出为True
    3. print(all(my_list)) # 输出为False

    10.使用sorted函数对可迭代对象进行排序

    1. my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    2. sorted_list = sorted(my_list)
    3. print(sorted_list) # 输出为[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

    11.使用set进行集合操作

    1. set1 = {1, 2, 3, 4, 5}
    2. set2 = {3, 4, 5, 6, 7}
    3. print(set1.union(set2)) # 输出为{1, 2, 3, 4, 5, 6, 7}
    4. print(set1.intersection(set2)) # 输出为{3, 4, 5}

    12.上下文管理器

    1. class CustomContextManager:
    2. def __enter__(self):
    3. # 在代码块执行之前执行的操作
    4. # 可以返回一个值,该值将被赋值给as子句中的变量
    5. def __exit__(self, exc_type, exc_val, exc_tb):
    6. # 在代码块执行之后执行的操作
    7. # 可以处理异常,返回True表示异常被处理,False则会重新抛出异常
    8. # 使用自定义上下文管理器
    9. with CustomContextManager() as obj:
    10. # 在这里执行一些操作

    13.生成器表达式

    1. # 使用生成器表达式计算110的平方和
    2. squared_sum = sum(x**2 for x in range(1, 11))
    3. print(squared_sum)

    14.使用str.endswith()方法来检查字符串是否以元组中的任何一个字符串结尾

    1. filename = "example.csv"
    2. if filename.endswith((".csv", ".xls", ".xlsx")):
    3. # 执行相关操作

    同样的用法还有str.startswith()来检查字符串是否以元组中的任何一个字符串开头

    15.else语句与for和while循环结合使用

    1. for item in some_list:
    2. if condition:
    3. # 执行相关操作
    4. break
    5. else:
    6. # 如果循环自然结束,执行相关操作

    16.静态类型检查

    1. # 使用mypy进行静态类型检查
    2. def add_numbers(a: int, b: int) -> int:
    3. return a + b
    4. result = add_numbers(5, 10)
    5. print(result)

    先总结这么多,欢迎补充

    文章转载自:ops-coffee

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

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

  • 相关阅读:
    (区别、详解、使用)module.exports与exports,export与export default,import 与require
    【JVM】运行时数据区之 堆——自问自答
    HTML+CSS简单的网页制作期末作业——浙江旅游景点介绍网页制作
    归并排序和计数排序
    1.UEFI环境搭建
    解决github ping不通的问题(1024程序员节快乐!
    LeetCode-775-全局倒置与局部倒置
    【SpringBoot笔记27】SpringBoot集成ES数据库之操作index索引(创建、删除、获取)
    Python基本语法_集合setfrozenset_内建方法详解
    2022年您应该考虑使用的最佳WordPress主题
  • 原文地址:https://blog.csdn.net/sdgfafg_25/article/details/136553377