【Python】编程50个经典操作

一、字符串操作

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
相关推荐
清水白石008几秒前
STL性能优化实战:如何让C++程序畅快运行
开发语言·c++·性能优化
溯源00613 分钟前
pytorch中不同的mask方法:masked_fill, masked_select, masked_scatter
人工智能·pytorch·python
名字都被谁用了14 分钟前
Python入门(2)——变量命名规则与6大核心数据类型
开发语言·python·pycharm
可乐张20 分钟前
Qwen最新多模态大模型:Qwen2.5-Omni介绍与快速入门
人工智能·python·aigc
Ai 编码助手27 分钟前
PHP泛型与集合的未来:从动态类型到强类型的演进
java·python·php
权^29 分钟前
Java多线程与JConsole实践:从线程状态到性能优化!!!
java·开发语言·性能优化
学习同学31 分钟前
C++ 初阶总复习 (16~30)
开发语言·c++
Felven35 分钟前
C. The Legend of Freya the Frog
c语言·开发语言
₍˄·͈༝·͈˄*₎◞ ̑̑码44 分钟前
数组的定义与使用
数据结构·python·算法
Yvsanf1 小时前
C++细节知识for面试
开发语言·c++