-
列表排序:
pythonCopy code
my_list = [3, 1, 4, 1, 5, 9, 2] my_list.sort()
-
生成器表达式:
pythonCopy code
gen_exp = (x**2 for x in range(10)) for x in gen_exp: print(x)
-
字典推导式:
pythonCopy code
square_dict = {x: x**2 for x in range(5)}
-
集合推导式:
pythonCopy code
square_set = {x**2 for x in [1, -1, 2]}
-
使用zip合并序列:
pythonCopy code
names = ["Alice", "Bob", "Charlie"] scores = [85, 90, 88] for name, score in zip(names, scores): print(f"{name}: {score}")
-
文件逐行读取:
pythonCopy code
with open("myfile.txt", "r") as file: for line in file: print(line.strip())
-
使用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))
-
使用reduce函数:
pythonCopy code
from functools import reduce numbers = [1, 2, 3, 4] sum = reduce(lambda x, y: x + y, numbers)
-
列表中的元素计数:
pythonCopy code
from collections import Counter myList = [1, 2, 3, 4, 1, 2, 6, 7, 3, 8, 1] count = Counter(myList) print(count[1]) # 输出1出现的次数
-
正则表达式匹配:
pythonCopy code
import re pattern = r"\d+" string = "There are 123 numbers in this sentence." result = re.findall(pattern, string) print(result)
-
使用datetime模块:
pythonCopy code
from datetime import datetime now = datetime.now() print(f"Current date and time: {now}")
-
环境变量读取:
pythonCopy code
import os home_directory = os.getenv("HOME") print(home_directory)
-
执行系统命令:
pythonCopy code
import os os.system("echo Hello, world!")
-
使用argparse处理命令行参数:
pythonCopy code
import argparse parser = argparse.ArgumentParser(description="Example script.") parser.add_argument("--name", help="Your name") args = parser.parse_args() print(f"Hello, {args.name}")
-
JSON数据处理:
pythonCopy code
import json data = {"name": "John", "age": 30, "city": "New York"} json_string = json.dumps(data) # 将字典转换为JSON字符串 new_data = json.loads(json_string) # 将JSON字符串转换回字典
-
使用requests模块发送HTTP请求:
pythonCopy code
import requests response = requests.get('https://api.github.com') data = response.json()
这里提供了一个广泛的Python代码示例集合,覆盖了多个主题和应用场景。希望这能够帮助你更好地了解和学习Python的各种功能和用法。如果你有特定的需求或想深入了解某个话题,请随时提问!