经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
Python中那些简单又好用的特性和用法 - ops-coffee
来源:cnblogs  作者:ops-coffee  时间:2024/3/7 9:10:56  对本文有异议

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.链式赋值

  1. 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. # 使用生成器表达式计算1到10的平方和
  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)

先总结这么多,欢迎补充

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号