当前位置: 首页 > 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.")


http://www.mrgr.cn/news/6515.html

相关文章:

  • 喜报 | 麒麟信安“信创云桌面解决方案”在浙江省委党校应用实施,荣膺国家级示范案例
  • 浅谈对Maven的理解
  • 【工作记录】springboot中基于redis实现地理位置相关需求@20240822
  • 【功能自动化】WebTours:使用unittest编写注册测试用例
  • NACOS 2.4.1如何开启账号密码登录功能
  • 如何在没有密码的情况下解锁iPhone?
  • 探索OpenCV:计算机视觉的入门指南
  • ThreeJS中如何播放mp3音频?
  • 单例模式(singleton)- python实现
  • MySQL事务
  • 掌握Core Motion:Swift中运动传感器的魔法
  • 判别分析2|Bayes判别分析|Fisher判别分析|软件求解
  • Apollo9.0 PNC源码学习之Planning模块—— Lattice规划(六):横纵向运动轨迹评估
  • 小编需复盘,写练习
  • Vue3 后台管理系统项目 前端部分
  • 电脑换硬盘怎么全盘克隆?轻松实现数据迁移
  • 在SpringBoot中优雅整合MongoDB——让你的数据存储更灵活
  • 东方银行--用 MinIO 和 Dremio 替代 Hadoop
  • 文件操作
  • c++链表(list)