-
使用zip:
pythonCopy code
names = ["Anna", "Bob", "Charlie"] scores = [85, 90, 88] for name, score in zip(names, scores): print(f"{name}: {score}")
-
列表排序:
pythonCopy code
numbers = [3, 1, 4, 1, 5, 9, 2] numbers.sort()
-
字符串分割和连接:
pythonCopy code
sentence = "This is a sentence" words = sentence.split(" ") rejoined = " ".join(words)
-
格式化字符串:
pythonCopy code
name = "Alice" age = 30 print(f"{name} is {age} years old.")
-
Lambda函数:
pythonCopy code
square = lambda x: x * x print(square(5))
-
map函数:
pythonCopy code
numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers))
-
filter函数:
pythonCopy code
numbers = [1, 2, 3, 4, 5, 6] even = list(filter(lambda x: x % 2 == 0, numbers))
-
生成器表达式:
pythonCopy code
squares_gen = (x**2 for x in range(10)) for square in squares_gen: print(square)
-
集合推导式:
pythonCopy code
squared_set = {x**2 for x in range(-5, 6)}
-
字典推导式:
pythonCopy code
square_dict = {x: x**2 for x in range(5)}
-
使用try和except捕获特定异常:
pythonCopy code
try: # risky code result = 1 / 0 except ZeroDivisionError as e: print(f"Error: {e}")
-
模块导入:
pythonCopy code
import math print(math.sqrt(16))
-
从模块导入特定函数:
pythonCopy code
from math import sqrt print(sqrt(16))
-
创建自定义模块并导入:
pythonCopy code
# Assume this is in a file named mymodule.py def my_function(): return "Hello from my module!" # In another Python file from mymodule import my_function print(my_function())
-
文件和目录操作:
pythonCopy code
import os os.rename("oldname.txt", "newname.txt") os.remove("myfile.txt") os.mkdir("newdir") os.rmdir("newdir") print(os.getcwd())
-
正则表达式匹配:
pythonCopy code
import re result = re.match(r'^\d+', '123abc') if result: print(result.group())
-
环境变量访问:
pythonCopy code
import os path = os.environ.get('PATH') print(path)
-
列表内的最大值和最小值:
pythonCopy code
numbers = [1, 2, 3, 4, 5] print(max(numbers)) print(min(numbers))
-
字符串大小写转换:
pythonCopy code
message = "Hello World" print(message.lower()) print(message.upper())
-
判断字符串是否为数字:
pythonCopy code
s = "123" print(s.isdigit())
-
切片反转字符串:
pythonCopy code
s = "Hello" reversed_s = s[::-1] print(reversed_s)
-
使用enumerate获取索引和值:
pythonCopy code
for index, value in enumerate(["a", "b", "c"]): print(f"Index: {index}, Value: {value}")
100个python代码(二)
本文概述了Python编程中的各种基础概念和技术,包括使用zip函数,列表排序,字符串操作,格式化输出,以及Lambda、map、filter、生成器和集合推导等高级功能。同时涉及异常处理、模块管理、文件和目录操作、正则表达式、环境变量、数据处理等实用技巧。
摘要由CSDN通过智能技术生成