30 个即用的 Python 常用极简代码

2024-12-31 09:20:14   小编

30 个即用的 Python 常用极简代码

在 Python 编程的世界里,掌握一些常用的极简代码片段可以极大地提高我们的工作效率。以下为您精心整理了 30 个实用的 Python 极简代码示例,希望能对您有所帮助。

  1. 交换两个变量的值 a, b = b, a

  2. 生成一个指定范围内的随机整数 import random random.randint(start, end)

  3. 计算列表中元素的平均值 sum(lst) / len(lst)

  4. 找出列表中的最大值 max(lst)

  5. 找出列表中的最小值 min(lst)

  6. 对列表进行排序 lst.sort()

  7. 反转列表 lst.reverse()

  8. 检查一个元素是否在列表中 if element in lst:

  9. 计算字符串的长度 len(string)

  10. 检查字符串是否以指定的子字符串开头 string.startswith(substring)

  11. 检查字符串是否以指定的子字符串结尾 string.endswith(substring)

  12. 去除字符串两端的空格 string.strip()

  13. 将字符串转换为大写 string.upper()

  14. 将字符串转换为小写 string.lower()

  15. 分割字符串 string.split(separator)

  16. 连接列表中的字符串 " ".join(lst)

  17. 计算阶乘 def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n - 1)

  18. 判断一个数是否为偶数 if num % 2 == 0:

  19. 判断一个数是否为奇数 if num % 2!= 0:

  20. 计算两个数的最大公约数 def gcd(a, b): while b!= 0: a, b = b, a % b return a

  21. 计算两个数的最小公倍数 def lcm(a, b): return a * b // gcd(a, b)

  22. 生成一个包含指定数量元素的列表 [value for _ in range(count)]

  23. 筛选出列表中的奇数 [num for num in lst if num % 2!= 0]

  24. 筛选出列表中的偶数 [num for num in lst if num % 2 == 0]

  25. 计算列表中元素的和 sum(lst)

  26. 计算列表中元素的乘积 import functools functools.reduce(lambda x, y: x * y, lst)

  27. 复制一个列表 new_lst = lst.copy()

  28. 去除列表中的重复元素 list(set(lst))

  29. 计算列表中元素出现的次数 from collections import Counter Counter(lst)

  30. 遍历字典 for key, value in dict.items():

这些极简代码在日常的编程任务中经常会用到,熟练掌握它们将使您的 Python 编程之旅更加轻松高效。不断积累和运用这些代码片段,您将能够编写出更加简洁、优雅的 Python 代码。

TAGS: Python 示例 Python 代码 Python 应用 Python 技巧

欢迎使用万千站长工具!

Welcome to www.zzTool.com