技术文摘
30 个实用 Python 代码片段,30 秒内轻松学会
2024-12-31 11:28:24 小编
30 个实用 Python 代码片段,30 秒内轻松学会
Python 作为一种强大且易于学习的编程语言,拥有众多实用的代码片段,可以帮助我们快速解决各种问题。以下为您精心整理了 30 个实用的 Python 代码片段,让您在 30 秒内轻松学会!
- 交换两个变量的值
a, b = b, a
- 检查一个数是否为偶数
def is_even(n):
return n % 2 == 0
- 计算列表中元素的平均值
def average(lst):
return sum(lst) / len(lst)
- 反转字符串
def reverse_string(s):
return s[::-1]
- 查找列表中的最大值
def find_max(lst):
return max(lst)
- 计算阶乘
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
- 检查一个字符串是否为回文
def is_palindrome(s):
return s == s[::-1]
- 生成一个指定范围内的随机数
import random
def random_number(start, end):
return random.randint(start, end)
- 计算列表中元素的和
def sum_list(lst):
return sum(lst)
- 找出列表中出现次数最多的元素
from collections import Counter
def most_common(lst):
counter = Counter(lst)
return counter.most_common(1)[0][0]
- 去除列表中的重复元素
def remove_duplicates(lst):
return list(set(lst))
- 对列表进行排序
def sort_list(lst):
return sorted(lst)
- 计算两个数的最大公约数
def gcd(a, b):
while b!= 0:
a, b = b, a % b
return a
- 计算两个数的最小公倍数
def lcm(a, b):
return a * b // gcd(a, b)
- 判断一个数是否为质数
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
- 计算斐波那契数列
def fibonacci(n):
fib_seq = [0, 1]
while len(fib_seq) < n:
fib_seq.append(fib_seq[-1] + fib_seq[-2])
return fib_seq
- 合并两个字典
def merge_dictionaries(dict1, dict2):
return {**dict1, **dict2}
- 读取文件内容
def read_file(file_path):
with open(file_path, 'r') as file:
return file.read()
- 写入文件内容
def write_file(file_path, content):
with open(file_path, 'w') as file:
file.write(content)
- 检查文件是否存在
import os
def file_exists(file_path):
return os.path.exists(file_path)
- 复制文件
import shutil
def copy_file(source_path, destination_path):
shutil.copy(source_path, destination_path)
- 删除文件
import os
def delete_file(file_path):
os.remove(file_path)
- 获取当前时间
import datetime
def get_current_time():
return datetime.datetime.now()
- 计算程序运行时间
import time
start_time = time.time()
# 这里是您的程序代码
end_time = time.time()
execution_time = end_time - start_time
print("程序运行时间:", execution_time, "秒")
- 生成指定长度的随机字符串
import random
import string
def generate_random_string(length):
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
- 列表推导式创建列表
squares = [x**2 for x in range(10)]
- 字典推导式创建字典
squares_dict = {x: x**2 for x in range(10)}
- 过滤列表中的元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
- 映射列表中的元素
numbers = [1, 2, 3, 4, 5]
doubled_numbers = [num * 2 for num in numbers]
- 遍历字典
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
print(key, value)
这些实用的 Python 代码片段能够帮助您在日常编程中提高效率,节省时间。希望您能够熟练掌握并灵活运用它们!
TAGS: Python 编程 编程技巧 Python 代码片段 代码学习
- React Router DOM 的使用方法
- 微服务的一切您都需要了解
- JavaScript里for循环的类型
- 软件开发生命周期 (SDLC) 全面指南
- 让无头组件设计更轻松
- Laravel与jQuery结合实现无限滚动
- 深入了解 GitHub Webhook:全方位指南
- Leetcode 允许一个函数调用
- 乐观UI提升前端应用用户体验
- ReactNode与ReactElement差异解析
- 编码训练营:是投资还是风险
- Jest JS 单元测试经验分享
- Recharts:React图表库的终极之选
- Algolia和Elasticsearch:如何选择正确的搜索解决方案
- #daysofMiva 编码挑战日:把JavaScript链接到HTML文件