fizz_buzz_list =["FizzBuzz"if i %15==0else"Fizz"if i %3==0else"Buzz"if i %5==0else i for i inrange(1,101)]print(fizz_buzz_list)
这个例子展示了列表推导式,用于生成FizzBuzz序列。
2. 使用with语句和csv模块读取CSV文件
import csv
withopen('data.csv', mode='r')asfile:
csvFile = csv.reader(file)for row in csvFile:print(row)
csv模块是处理CSV文件的利器,与with语句结合可以确保文件正确关闭。
3. 正则表达式查找字符串
import re
pattern =r'\b[A-Za-z][A-Za-z0-9_]*\b'
text ="Hello, this is a test string with username: JohnDoe"
matches = re.findall(pattern, text)print(matches)
正则表达式是强大的文本匹配工具,这里用来找出字符串中的所有单词。
4. 计算字符串中某个字符的数量
text ="Hello, World!"
char ="l"
count = text.count(char)print(f"The character '{char}' appears {count} times.")
name ="John"
age =30print("My name is {} and I am {} years old.".format(name, age))
format() 方法使字符串格式化更加灵活和清晰。
7. 实现一个简单的缓存装饰器
defcache(func):
cache_dict ={}defwrapper(num):if num in cache_dict:return cache_dict[num]else:
val = func(num)
cache_dict[num]= val
return val
return wrapper
@cachedeffibonacci(n):if n <2:return n
return fibonacci(n-1)+ fibonacci(n-2)print(fibonacci(10))
装饰器可以用来缓存函数的结果,提高性能。
8. 使用try-except-else-finally处理异常
try:
result =10/0except ZeroDivisionError:print("Cannot divide by zero")else:print("Result is:", result)finally:print("Execution complete.")
完整的异常处理流程可以让我们更好地控制程序执行。
9. 断言(assertion)的使用
defdivide(a, b):assert b !=0,"Division by zero is not allowed"return a / b
print(divide(10,0))
import threading
defprint_numbers():for i inrange(10):print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
threading模块允许我们创建和管理线程,这是实现并发的一种方式。
19. 使用multiprocessing模块进行多进程编程
from multiprocessing import Process, cpu_count
defprint_hello():print("Hello from child process")if __name__ =='__main__':
processes =[]for _ inrange(cpu_count()):
p = Process(target=print_hello)
p.start()
processes.append(p)for p in processes:
p.join()
name ="John"
age =30print(f"My name is {name} and I am {age} years old.")
字符串格式化是Python中处理字符串的重要方法。
28. 异常处理
try:
result =10/0except ZeroDivisionError:print("Cannot divide by zero")
异常处理可以帮助我们捕获和处理错误。
29. 类定义
classPerson:def__init__(self, name, age):
self.name = name
self.age = age
defgreet(self):print(f"Hello, my name is {self.name} and I am {self.age} years old.")