一、字符串操作
1、字符串反转
python
s = "hello"
print(s[::-1]) # olleh
2、字符串拼接
python
words = ["python", "is", "awesome"]
print(" ".join(words)) # python is awesome
3、字符串格式化(f-string)
python
name = "Alice"
age = 25
print(f"{name} is {age} years old.") # Alice is 25 years old.
4、分割字符串成列表
python
text = "apple,banana,cherry"
print(text.split(",")) # ['apple', 'banana', 'cherry']
5、替换字符串内容
python
s = "I like C"
print(s.replace("C", "Python")) # I like Python
二、列表操作
1、列表去重
python
lst = [1, 2, 2, 3, 4, 6, 3, 4, 2]
unique = list(set(lst))
print(unique) # [1, 2, 3, 4, 6]
2、列表推导式
python
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
3、过滤列表中的元素
bash
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
event = [x for x in numbers if x % 2 == 0]
print(event) # [2, 4, 6, 8]
4、列表排序(原地修改)
python
lst2 = [3, 1, 6, 5, 7, 2]
lst2.sort()
print(lst2) # [1, 2, 3, 5, 6, 7]
5、合并两个列表
python
list1 = [1, 3]
list2 = [5, 6]
merged = list1 + list2
print(merged) # [1, 3, 5, 6]
三、字典操作
1、合并字典
python
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'d': 4, 'e': 5}
merged = {**dict1, **dict2}
print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
2、字典推导式
python
squares = {x: x ** 2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
3、获取字典默认值
python
d = {'a': 2}
value = d.get('a', 0)
print(value) # 2
4、遍历字典键值对
python
d = {'a': 3, 'b': 6, 'c': 9}
for key, value in d.items():
print(key, value)
# a 3
# b 6
# c 9
5、字典按值排序
python
d = {'a': 3, 'l': 6, 'g': 9, 'd': 7, 'e': 8, 'f': 10, }
sorted_d = sorted(d.items(), key=lambda x: x[1])
print(sorted_d) # [('a', 3), ('l', 6), ('d', 7), ('e', 8), ('g', 9), ('f', 10)]
四、文件操作
首先先file.txt文件中写入内容
1、读取文件内容
python
with open('file.txt', 'r') as f:
content = f.read()
print(content)
# hello world
# I like Python
# This is my first Python
2、逐行读取文件
python
with open('file.txt', 'r') as f:
lines = [line.strip() for line in f.readlines()]
print(lines) # ['hello world', 'I like Python', 'This is my first Python']
3、写入文件
python
with open('output.txt', 'w') as f:
f.write("Hello Python!") # output.txt中将写入
4、追加内容到文件
python
with open('output.txt', 'a') as f:
f.write("new log entry\n") # output.txt中将追加
5、处理CSV文件
python
import csv
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
五、函数与类
1、默认参数函数
python
def greet(name="world"):
print(f"Hello {name}")
greet()
2、**可变参数(*args和kwargs)
python
def func(*args, **kwargs):
print(args, kwargs)
# 不传入任何参数
func()
# 只传入非关键字参数
func(1, 2, 3)
# 只传入关键字参数
func(a=10, b=20)
# 同时传入非关键字参数和关键字参数
func(1, 2, a=10, b=20)
3、Lambda函数
python
add = lambda x, y: x + y
print(add(1, 2)) # 3
4、装饰器
python
def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@my_decorator
def say_hello():
print("Hello")
say_hello()
# Before function
# Hello
# After function
5、类的继承
python
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("I am a dog")
dog = Dog()
dog.speak() # I am a dog
六、数据处理
1、使用map函数
python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81]
2、使用filter函数
python
numbers = [1, 2, 3, 4, 5]
event = list(filter(lambda x: x % 2 == 0, numbers))
print(event) # [2, 4]
3、使用zip合并列表
python
names = ["Alice", "Bob", "Carol"]
ages = [25, 30, 26]
combined = list(zip(names, ages))
print(combined) # [('Alice', 25), ('Bob', 30), ('Carol', 26)]
4、列表展开(扁平化)
python
nested = [[1, 2], [3, 4]]
float = [item for sublist in nested for item in sublist]
print(float) # [1, 2, 3, 4]
5、统计元素频率
python
from collections import Counter
lst = ['a', 'b', 'c', 'd', 'e', 'a', 'a']
count = Counter(lst)
print(count)
七、实用技巧
1、交换变量值
python
a, b = 1, 3
a, b = b, a
print(a, b) # 3 1
2、链式比较
python
x = 5
if 0<x<10:
print("Valid")#Valid
3、三元表达式
python
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) #Adult
4、生成随机数
python
import random
print(random.randint(1,10)) # 随机取1-10中间的整数
5、时间戳转换
python
import time
timestamp = time.time()
local_time = time.localtime(timestamp)
print(local_time)
八、高级操作
1、生成器表达式
python
gen = (x**2 for x in range(5))
for num in gen:
print(num)
2、上下管理器(自定义)
python
class MyContextManager:
def __enter__(self):
print("Entering context")
def __exit__(self, type, value, traceback):
print("Exiting context")
with MyContextManager():
print("Inside the context")
3、枚举遍历
python
fruit = ["apple", "banana", "cherry"]
for index,fruit in enumerate(fruit):
print(index, fruit)
#0 apple
#1 banana
#2 cherry
4、递归目录遍历
python
import os
for root,dirs,files in os.walk("."):
print(root)
5、使用collections.defaultdict
python
from collections import defaultdict
d = defaultdict(int)
d['a'] +=1
九、网络与模块
1、发送HTTP请求
python
import requests
response = requests.get("http://www.python.org/")
print(response.json())
2、解析JSON
python
import json
data ='{"name":"Alice","age":25}'
obj = json.loads(data)
print(obj)
3、读取环境变量
python
import os
api_key = os.getenv("API_KEY")
4、命令行参数解析
python
import sys
args = sys.argv[1:]
5、使用argparse模块
python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input',help='Input file')
args = parser.parse_args()
十、算法与数学
1、斐波拉契数列(生成器)
python
def fibonacci(n):
a,b = 0,1
for i in range(n):
yield a
a,b = b,a+b
print(list(fibonacci(5)))
2、判断质数
python
def is_prime(n):
if n <= 2:
return False
for i in range(3,int(n**0.5)+1):
if n % i == 0:
return False
return True
3、列表元素排列组合
python
import itertools
lst = [1,2,3]
perms = list(itertools.permutations(lst))
combs = list(itertools.combinations(perms, 2))
4、快速排序
python
def quicksort(lst):
if len(lst) <=1:
return lst
pivot = lst[len(lst)//2]
left = [x for x in lst if x < pivot]
middle = [x for x in lst if x == pivot]
right = [x for x in lst if x > pivot]
return quicksort(left) + middle + quicksort(right)
5、类型提示
python
def add(a:int,b:int)->int:
return a+b