当前位置: 首页 > news >正文

总结:Python语法

Python中的字典、列表和数组是三种常用的数据结构,它们各自有不同的用途和特性。

字典(Dictionary)

字典是一种无序的、可变的数据结构,它存储键值对(key-value pairs)。字典中的每个元素都是一个键值对,键是唯一的。

特性

  • 通过键来访问元素。
  • 键必须是不可变类型,如字符串、数字或元组。
  • 值可以是任何数据类型。
# 创建一个空字典
my_dict = {}# 创建一个包含键值对的字典
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}# 访问字典中的值
print(my_dict['name'])  # 输出: Alice
print(my_dict.get('age'))  # 输出: 25# 更新字典中的值
my_dict['age'] = 26
print(my_dict['age'])  # 输出: 26# 添加新的键值对
my_dict['country'] = 'USA'
print(my_dict)  # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA'}# 删除字典中的键值对
del my_dict['city']
print(my_dict)  # 输出: {'name': 'Alice', 'age': 26, 'country': 'USA'}# 使用pop方法删除并返回键对应的值
popped_value = my_dict.pop('age')
print(popped_value)  # 输出: 26
print(my_dict)  # 输出: {'name': 'Alice', 'country': 'USA'}# 检查字典中是否包含某个键
if 'name' in my_dict:print("Name is present")
else:print("Name is not present")# 遍历字典中的键
for key in my_dict.keys():print(key)# 遍历字典中的值
for value in my_dict.values():print(value)# 遍历字典中的键值对
for key, value in my_dict.items():print(f"{key}: {value}")# 复制字典
dict_copy = my_dict.copy()
print(dict_copy)  # 输出: {'name': 'Alice', 'country': 'USA'}# 清空字典
my_dict.clear()
print(my_dict)  # 输出: {}

列表(List)

列表是一种有序的、可变的数据结构,可以包含任意类型的元素,包括其他列表。

特性

  • 通过索引来访问元素,索引从0开始。
  • 可以包含重复的元素。
  • 支持增加、删除、修改和排序操作。
# 导入必要的库
import random# 创建一个列表
my_list = [1, 2, 3, 'hello', 3.14]# 访问列表中的元素
print(my_list[0])  # 输出: 1
print(my_list[-1])  # 输出: 3.14# 修改列表中的元素
my_list[0] = 'one'
print(my_list)  # 输出: ['one', 2, 3, 'hello', 3.14]# 添加元素到列表末尾
my_list.append('new item')
print(my_list)  # 输出: ['one', 2, 3, 'hello', 3.14, 'new item']# 插入元素到指定位置
my_list.insert(2, 'inserted')
print(my_list)  # 输出: ['one', 2, 'inserted', 3, 'hello', 3.14, 'new item']# 扩展列表
my_list.extend(['apple', 'banana'])
print(my_list)  # 输出: ['one', 2, 'inserted', 3, 'hello', 3.14, 'new item', 'apple', 'banana']# 删除列表中的元素
del my_list[2]
print(my_list)  # 输出: ['one', 2, 3, 'hello', 3.14, 'new item', 'apple', 'banana']# 移除列表中的特定值
my_list.remove('hello')
print(my_list)  # 输出: ['one', 2, 3, 3.14, 'new item', 'apple', 'banana']# 使用列表推导式生成新列表
squared_list = [x**2 for x in my_list if isinstance(x, int)]
print(squared_list)  # 输出: [1, 4, 9]# 使用random模块生成随机列表
random_list = [random.randint(1, 10) for _ in range(10)]
print(random_list)  # 输出: 例如: [5, 2, 9, 1, 7, 6, 3, 8, 10, 4]# 使用zip函数合并多个列表
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
combined_list = list(zip(names, ages))
print(combined_list)  # 输出: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]# 使用enumerate函数遍历带索引的列表
for index, value in enumerate(my_list):print(f"Index {index}: {value}")# 使用sorted函数对列表排序
sorted_list = sorted(my_list, key=lambda x: str(x))
print(sorted_list)  # 输出: 排序后的列表
  1. 使用del语句删除元素del fruits[2]这行代码的意思是删除列表fruits中索引为2的元素。在Python中,索引是从0开始的,所以这将删除第三个元素。假设fruits列表开始时包含['apple', 'banana', 'cherry', 'mango'],执行这行代码后,列表将变为['apple', 'banana', 'mango']

  2. 使用pop()方法删除元素fruits.pop()这行代码调用了列表的pop方法,不带任何参数时,pop方法会删除并返回列表中的最后一个元素。继续上面的例子,如果列表现在是['apple', 'banana', 'mango'],执行fruits.pop()后,列表将变为['apple', 'banana'],并且pop方法会返回被删除的元素'mango'

切片语法list_name[start:end],其中:

       start 是切片开始的索引(包含该索引位置的元素)。

       end 是切片结束的索引(不包含该索引位置的元素)。


数组(Array)

在Python中,数组通常指的是使用NumPy库创建的数组。NumPy是一个用于科学计算的库,提供了高性能的数组对象。

特性

  • 元素类型统一。
  • 通过索引访问元素,索引从0开始。
  • 通常用于数值计算和多维数据集。
import numpy as np# 创建一个 NumPy 数组
my_array = np.array([1, 2, 3, 4, 5])# 访问数组中的元素
print(my_array[0])  # 输出: 1
print(my_array[-1])  # 输出: 5# 修改数组中的元素
my_array[0] = 10
print(my_array)  # 输出: [10  2  3  4  5]# 数组间的数学运算,对应加起来
another_array = np.array([6, 7, 8, 9, 10])
result_array = my_array + another_array
print(result_array)  # 输出: [16  9 11 13 15]# 使用 NumPy 函数
mean_value = np.mean(my_array) #平均数
print(mean_value)  # 输出: 5.0# 生成随机数组
random_array = np.random.randint(1, 10, size=(3, 3))
print(random_array)  # 输出: 例如:
# [[3 7 2]
#  [4 1 6]
#  [8 9 5]]# 数组拼接
concatenated_array = np.concatenate((my_array, another_array))
print(concatenated_array)  # 输出: [10  2  3  4  5  6  7  8  9 10]# 数组转置
transposed_array = np.transpose(random_array)
print(transposed_array)  # 输出: 例如:
# [[3 4 8]
#  [7 1 9]
#  [2 6 5]]# 数组分割
split_arrays = np.split(random_array, 3, axis=1)
print(split_arrays)  # 输出: 例如:
# [array([[3],
#         [4],
#         [8]]),
#  array([[7],
#         [1],
#         [9]]),
#  array([[2],
#         [6],
#         [5]])]# 数组索引和切片
print(random_array[0, :])  # 输出: 例如: [3 7 2],第一列
print(random_array[:, 1])  # 输出: 例如: [7 1 9],第二行


Python中的数组和列表有以下主要区别

  1. 数据类型

    • 列表(List):可以存储不同类型的元素,如整数、浮点数、字符串、元组等,甚至是其他列表。
    • 数组(Array):通常指的是NumPy库中的数组,它们要求所有元素必须是相同类型的,例如全部为整数或全部为浮点数。
  2. 性能

    • 列表由于其灵活性(可以存储不同类型的元素),在内存使用和性能上可能不如数组高效。
    • 数组由于元素类型一致,可以进行优化,因此在数值计算和大规模数据处理时通常比列表有更好的性能。
  3. 功能

    • 列表提供了丰富的方法,如append()remove()pop()reverse()等,用于添加、删除和修改元素。
    • 数组虽然也有类似的功能,但NumPy库提供的数组更专注于数值计算,提供了大量的数学和统计方法,如sum()mean()max()等。

文件操作

# 导入os模块,用于获取当前工作目录
import os# 获取当前工作目录
current_directory = os.getcwd()
print(f"Current Working Directory: {current_directory}")# 定义文件路径
file_path = os.path.join(current_directory, 'example.txt')# 1. 创建并写入文件
# 使用 'w' 模式打开文件,如果文件已存在则会被覆盖
with open(file_path, 'w') as file:file.write("Hello, world!\n")file.write("This is an example text file.\n")file.write("We can write multiple lines to it.\n")# 2. 读取文件
# 使用 'r' 模式打开文件,用于读取
with open(file_path, 'r') as file:content = file.read()print("File Content:")print(content)# 3. 追加内容到文件
# 使用 'a' 模式打开文件,用于追加内容
with open(file_path, 'a') as file:file.write("This line was added later.\n")# 4. 再次读取文件以验证追加的内容
with open(file_path, 'r') as file:content = file.readlines()print("\nFile Content after appending:")for line in content:print(line.strip())# 5. 使用 'rb' 模式读取二进制文件
# 创建一个二进制文件
binary_file_path = os.path.join(current_directory, 'example.bin')
with open(binary_file_path, 'wb') as binary_file:binary_file.write(b'\x00\x01\x02\x03\x04')# 读取二进制文件
with open(binary_file_path, 'rb') as binary_file:binary_content = binary_file.read()print("\nBinary File Content:")print(binary_content)# 6. 使用 'w+' 模式读写文件
# 'w+' 模式允许读写文件,但会覆盖原有内容
with open(file_path, 'w+') as file:file.write("New first line.\n")file.seek(0)  # 将文件指针移动到文件开头content = file.read()print("\nFile Content after using 'w+':")print(content)# 7. 使用 'a+' 模式追加并读取文件
# 'a+' 模式允许在文件末尾追加内容并读取现有内容
with open(file_path, 'a+') as file:file.write("New last line added with 'a+'.\n")file.seek(0)  # 将文件指针移动到文件开头content = file.read()print("\nFile Content after using 'a+':")print(content)# 8. 使用 'x' 模式创建文件
# 'x' 模式用于创建新文件,如果文件已存在,则会引发 FileExistsError
try:with open(os.path.join(current_directory, 'new_example.txt'), 'x') as new_file:new_file.write("This is a new file created with 'x'.\n")
except FileExistsError:print("The file already exists.")# 9. 使用 'b' 模式处理二进制文件
# 读取二进制文件并写入另一个文件
with open(binary_file_path, 'rb') as source_binary_file:with open(os.path.join(current_directory, 'copy_example.bin'), 'wb') as dest_binary_file:dest_binary_file.write(source_binary_file.read())

 这段代码包含了以下文件操作的基本功能:

  1. 创建并写入文件。
  2. 读取文件内容。
  3. 追加内容到文件。
  4. 读取二进制文件。
  5. 使用 'w+' 模式读写文件。
  6. 使用 'a+' 模式追加并读取文件。
  7. 使用 'x' 模式创建新文件。
  8. 处理二进制文件。

目录访问

import os# 1. 获取当前工作目录
current_directory = os.getcwd()
print(f"Current Working Directory: {current_directory}")# 2. 创建目录
directory_name = "example_dir"
directory_path = os.path.join(current_directory, directory_name)# 如果目录不存在,则创建它
if not os.path.exists(directory_path):os.makedirs(directory_path)print(f"Directory '{directory_name}' created.")
else:print(f"Directory '{directory_name}' already exists.")# 3. 列出目录内容
print("\nDirectory Contents:")
for filename in os.listdir(directory_path):print(filename)# 4. 列出所有子目录和文件
print("\nSubdirectories and Files:")
for root, dirs, files in os.walk(directory_path):level = root.replace(current_directory, '').count(os.sep)indent = ' ' * 4 * (level)print('{}{}/'.format(indent, os.path.basename(root)))subindent = ' ' * 4 * (level + 1)for f in files:print('{}{}'.format(subindent, f))# 5. 删除目录
# 首先确保目录为空或递归删除非空目录
if os.path.exists(directory_path):try:os.rmdir(directory_path)print(f"Directory '{directory_name}' removed.")except OSError:# 如果目录非空,则使用 shutil.rmtree 进行递归删除import shutilshutil.rmtree(directory_path)print(f"Directory '{directory_name}' and its contents removed.")
else:print(f"Directory '{directory_name}' does not exist.")

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • [JAVA]初识线程池及其基本应用
  • leetcode406:根据身高重建队列
  • FastDFS的安装(分布式项目中的图片管理)
  • 《晶核》服务器架构——第二篇
  • fastap之使用 contextvars 实现上下文变量
  • Ps:首选项 - 常规
  • Unity+Addressable
  • 15.CentOS7升级内核
  • Android 关于设备定屏/黑屏/冻屏/ANR那些事
  • 【北京仁爱堂】脖子歪斜,拉扯疼痛怎么办?规律的生活让痉挛性斜颈的恢复事半功倍!
  • 微信小程序登陆
  • 【精选】基于springboot个人理财APP(源码+设计+辅导)
  • MATLAB 低版本Matlab-读取LAS格式点云文件并可视化(78)
  • C++ 设计模式——迭代器模式
  • 令牌和签名详细介绍+开发使用教程
  • 【402天】跃迁之路——程序员高效学习方法论探索系列(实验阶段159-2018.03.14)...
  • 2017 年终总结 —— 在路上
  • gitlab-ci配置详解(一)
  • leetcode386. Lexicographical Numbers
  • python docx文档转html页面
  • tweak 支持第三方库
  • ⭐ Unity 开发bug —— 打包后shader失效或者bug (我这里用Shader做两张图片的合并发现了问题)
  • webpack项目中使用grunt监听文件变动自动打包编译
  • 给github项目添加CI badge
  • 机器人定位导航技术 激光SLAM与视觉SLAM谁更胜一筹?
  • 基于webpack 的 vue 多页架构
  • 快速构建spring-cloud+sleuth+rabbit+ zipkin+es+kibana+grafana日志跟踪平台
  • 设计模式 开闭原则
  • 深度解析利用ES6进行Promise封装总结
  • 腾讯优测优分享 | Android碎片化问题小结——关于闪光灯的那些事儿
  • 用 Swift 编写面向协议的视图
  • SAP CRM里Lead通过工作流自动创建Opportunity的原理讲解 ...
  • 京东物流联手山西图灵打造智能供应链,让阅读更有趣 ...
  • ​​​​​​​​​​​​​​汽车网络信息安全分析方法论
  • ## 临床数据 两两比较 加显著性boxplot加显著性
  • #php的pecl工具#
  • (2024.6.23)最新版MAVEN的安装和配置教程(超详细)
  • (LeetCode C++)盛最多水的容器
  • (附源码)ssm基于web技术的医务志愿者管理系统 毕业设计 100910
  • (附源码)计算机毕业设计ssm-Java网名推荐系统
  • (论文阅读22/100)Learning a Deep Compact Image Representation for Visual Tracking
  • (十六)串口UART
  • (五)Python 垃圾回收机制
  • (已更新)关于Visual Studio 2019安装时VS installer无法下载文件,进度条为0,显示网络有问题的解决办法
  • (转)ABI是什么
  • .bat批处理(一):@echo off
  • .NET 通过系统影子账户实现权限维持
  • .NET/ASP.NETMVC 深入剖析 Model元数据、HtmlHelper、自定义模板、模板的装饰者模式(二)...
  • .NET编程C#线程之旅:十种开启线程的方式以及各自使用场景和优缺点
  • .net快速开发框架源码分享
  • .net项目IIS、VS 附加进程调试
  • .NET中使用Redis (二)
  • /bin/bash^M: bad interpreter: No such file ordirectory
  • @ModelAttribute 注解
  • [ 云计算 | AWS ] 对比分析:Amazon SNS 与 SQS 消息服务的异同与选择