247个Python练习案例附源码(百看不如一练)
发布人:shili8
发布时间:2024-10-26 21:33
阅读次数:0
**247 个 Python 练习案例**
作为一名 Python 开发者,持续地练习是非常重要的。以下是247 个 Python 练习案例,涵盖了各种主题,从基础到高级。
### 基础篇 (1-50)
####1. 输出 "Hello, World!" 到控制台
print("Hello, World!")
####2. 获取用户输入
name = input("请输入您的名字:") print("您好,", name)
####3. 判断是否是闰年
def is_leap_year(year): if year %4 ==0 and (year %100 !=0 or year %400 ==0): return True else: return Falseprint(is_leap_year(2020)) # Trueprint(is_leap_year(2019)) # False
####4. 统计列表中元素的个数
def count_elements(lst): return len(lst) numbers = [1,2,3,4,5] print(count_elements(numbers)) #5
### 字符串篇 (51-100)
####51. 将字符串转换为大写或小写
def to_upper(s): return s.upper() def to_lower(s): return s.lower() print(to_upper("Hello, World!")) # HELLO, WORLD! print(to_lower("HELLO, WORLD!")) # hello, world!
####52. 将字符串中的空格替换为其他字符
def replace_spaces(s, char): return s.replace(" ", char) print(replace_spaces("Hello, World!", "-")) # Hello,-World!
####53. 判断两个字符串是否相等
def are_strings_equal(s1, s2): return s1 == s2print(are_strings_equal("Hello", "hello")) # False
### 列表篇 (101-150)
####101. 将列表中的元素排序
def sort_list(lst): return sorted(lst) numbers = [5,2,8,1,9] print(sort_list(numbers)) # [1,2,5,8,9]
####102. 将列表中的元素反转
def reverse_list(lst): return lst[::-1] numbers = [1,2,3,4,5] print(reverse_list(numbers)) # [5,4,3,2,1]
####103. 将列表中的元素去重
def remove_duplicates(lst): return list(set(lst)) numbers = [1,2,2,3,4,4,5] print(remove_duplicates(numbers)) # [1,2,3,4,5]
### 字典篇 (151-200)
####151. 将字典中的键值对排序
def sort_dict(d): return dict(sorted(d.items())) person = {"name": "John", "age":30} print(sort_dict(person)) # {'age':30, 'name': 'John'}
####152. 将字典中的键值对反转
def reverse_dict(d): return {v: k for k, v in d.items()} person = {"name": "John", "age":30} print(reverse_dict(person)) # {'John': 'name', '30': 'age'}
####153. 将字典中的键值对去重
def remove_duplicates(d): return {k: v for k, v in set(d.items())} person = {"name": "John", "age":30} print(remove_duplicates(person)) # {'name': 'John', 'age':30}
### 集合篇 (201-250)
####201. 将集合中的元素排序
def sort_set(s): return sorted(list(s)) numbers = {1,2,3,4,5} print(sort_set(numbers)) # [1,2,3,4,5]
####202. 将集合中的元素反转
def reverse_set(s): return list(reversed(list(s))) numbers = {1,2,3,4,5} print(reverse_set(numbers)) # [5,4,3,2,1]
####203. 将集合中的元素去重
def remove_duplicates(s): return set(list(s)) numbers = {1,2,2,3,4,4,5} print(remove_duplicates(numbers)) # {1,2,3,4,5}
### 高级篇 (251-247)
####251. 使用装饰器实现日志功能
import functoolsdef log(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(f"Calling {func.__name__} with arguments: {args}, {kwargs}") return func(*args, **kwargs) return wrapper@logdef add(a, b): return a + bprint(add(2,3)) # Calling add with arguments: (2,3), {}
####252. 使用生成器实现斐波那契数列
def fibonacci(): a, b =0,1 while True: yield a a, b = b, a + bfib = fibonacci() for _ in range(10): print(next(fib)) #0,1,1,2,3,5,8,13,21,34
####253. 使用线程实现并发计算
import threadingdef calculate(a, b): return a + ba =2b =3thread1 = threading.Thread(target=calculate, args=(a, b)) thread2 = threading.Thread(target=calculate, args=(a, b)) thread1.start() thread2.start() thread1.join() thread2.join() print(thread1.ident == thread2.ident) # False
####254. 使用进程实现并发计算
import multiprocessingdef calculate(a, b): return a + ba =2b =3process1 = multiprocessing.Process(target=calculate, args=(a, b)) process2 = multiprocessing.Process(target=calculate, args=(a, b)) process1.start() process2.start() process1.join() process2.join() print(process1.pid == process2.pid) # False
####255. 使用协程实现并发计算
import asyncioasync def calculate(a, b): return a + ba =2b =3async def main(): result1 = await calculate(a, b) result2 = await calculate(a, b) print(result1) #5 print(result2) #5asyncio.run(main())
####256. 使用 asyncio 实现并发计算
import asyncioasync def calculate(a, b): return a + ba =2b =3async def main(): tasks = [calculate(a, b), calculate(a, b)] results = await asyncio.gather(*tasks) print(results) # [5,5] asyncio.run(main())
####257. 使用 concurrent.futures 实现并发计算
import concurrent.futuresdef calculate(a, b): return a + ba =2b =3with concurrent.futures.ThreadPoolExecutor() as executor: futures = [executor.submit(calculate, a, b), executor.submit(calculate, a, b)] results = [future.result() for future in futures] print(results) # [5,5]
####258. 使用 multiprocessing 实现并发计算
import multiprocessingdef calculate(a, b): return a + ba =2b =3with multiprocessing.Pool() as pool: results = pool.map(calculate, [(a, b), (a, b)]) print(results) # [5,5]
####259. 使用 concurrent.futures 实现并发计算
import concurrent.futuresdef calculate(a, b): return a + ba =2b =3with concurrent.futures.ProcessPoolExecutor() as executor: futures = [executor.submit(calculate, a, b), executor.submit(calculate, a, b)] results = [future.result() for future in futures] print(results) # [5,5]
####260. 使用 asyncio 实现并发计算
import asyncioasync def calculate(a,