总结:Python语法

news/2024/9/18 15:05:09/ 标签: python, 开发语言

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

字典(Dictionary)

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

特性

  • 通过键来访问元素。
  • 键必须是不可变类型,如字符串、数字或元组。
  • 值可以是任何数据类型。
python"># 创建一个空字典
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开始。
  • 可以包含重复的元素。
  • 支持增加、删除、修改和排序操作。
python"># 导入必要的库
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开始。
  • 通常用于数值计算和多维数据集。
python">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()等。

文件操作

python"># 导入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. 处理二进制文件。

目录访问

python">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.ppmy.cn/news/1517042.html

相关文章

flink--会话模式与应用模式

flink-会话模式部署 会话情况&#xff1a; 添加依赖 <properties><flink.version>1.17.2</flink.version> </properties> ​ <dependencies><dependency><groupId>org.apache.flink</groupId><artifactId>flink-strea…

CSS属性

一、CSS列表样式 1、list-style-type属性&#xff08;列表项标记&#xff09; CSS列表属性允许我们设置不同的列表项标记。 在HTML中&#xff0c;有​两种类型​的列表&#xff1a; ​无序列表​&#xff08;<ul>&#xff09; - 列表项目用​项目符号​标记​有序列表…

【Linux】自动化构建工具makefile

目录 背景 makefile简单编写 .PHONY makefile中常用选项 makefile的自动推导 背景 会不会写makefile&#xff0c;从一个侧面说明了一个人是否具备完成大型工程的能力 ​ ◉ 一个工程中的源文件不计数&#xff0c;其按类型、功能、模块分别放在若干个目录中&#xff0c;mak…

开放式耳机怎么戴?佩戴舒适在线的几款开放式耳机分享

开放式耳机的佩戴方式与传统的入耳式耳机有所不同&#xff0c;它采用了一种挂耳式的设计&#xff0c;提供了一种新颖的佩戴体验&#xff0c;以下是开放式耳机的佩戴方式。 1. 开箱及外观&#xff1a;首先&#xff0c;从包装盒中取出耳机及其配件&#xff0c;包括耳机本体、充电…

使用 FinalShell 链接 Centos

1. 安装 FinalShell 下载地址&#xff1a;https://www.hostbuf.com/t/988.html 2. 查看 IP地址。 2.1 通过命令查询IP 输入 ip addr show 查询&#xff0c;输出效果如下截图&#xff0c;其中的 192.168.1.5 就是 IP 地址。 2.2 通过可视化界面查询IP 点击右上角的网络图标…

LoadBalancer负载均衡

一、概述 1.1、Ribbon目前也进入维护模式 Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。 简单的说&#xff0c;Ribbon是Netflix发布的开源项目&#xff0c;主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的…

企业中需要哪些告警Rules

文章目录 企业中需要哪些告警Rules前言定义告警规则企业中的告警rulesNode.rulesprometheus.ruleswebsite.rulespod.rulesvolume.rulesprocess.rules 总结 企业中需要哪些告警Rules 前言 Prometheus中的告警规则允许你基于PromQL表达式定义告警触发条件&#xff0c;Prometheus…

poi word 添加水印

poi word 添加水印 依赖DocxUtil调用遇到的问题部分客户给的word无法添加水印水印文案 过长会导致字变小变形 超过一定长度就会显示异常。消失等情况 依赖 <!--poi-tl--><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</art…

捕获神经网络的精髓:深入探索PyTorch的torch.jit.trace方法

标题&#xff1a;捕获神经网络的精髓&#xff1a;深入探索PyTorch的torch.jit.trace方法 在深度学习领域&#xff0c;模型的部署和优化是至关重要的环节。PyTorch作为最受欢迎的深度学习框架之一&#xff0c;提供了多种工具来帮助开发者优化和部署模型。torch.jit.trace是PyTo…

设计模式 10 外观模式

设计模式 10 创建型模式&#xff08;5&#xff09;&#xff1a;工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式结构型模式&#xff08;7&#xff09;&#xff1a;适配器模式、桥接模式、组合模式、装饰者模式、外观模式、享元模式、代理模式行为型模式&#xff…

ansible的tags标签

1、tags模块 可以给任务定义标签&#xff0c;可以根据标签来运行指定的任务 2、标签的类型 always&#xff1a;设定了标签名为always&#xff0c;除非指定跳过这个标签&#xff0c;否则该任务将始终会运行&#xff0c;即使指定了标签还会运行never&#xff1a;始终不运行的任…

CPU、MPU、MCU、SOC分别是什么?

CPU、MPU、MCU和SoC都是与微电子和计算机科学相关的术语&#xff0c;它们在功能定位、应用场景以及处理能力等方面有所区别。具体如下&#xff1a; CPU&#xff1a;CPU是中央处理单元的缩写&#xff0c;它通常指计算机内部负责执行程序指令的芯片。CPU是所有类型计算机&#x…

java 读取mysql中的表并按照指定格式导出excel

在Java中读取MySQL中的数据表并将其导出到Excel文件中&#xff0c;你需要以下几个步骤&#xff1a; 连接MySQL数据库&#xff1a;使用JDBC驱动程序连接到MySQL数据库。执行SQL查询&#xff1a;获取表数据。使用Apache POI库生成Excel文件&#xff1a;将数据写入Excel格式。保存…

SpringBoot文档之构建包的阅读笔记

Packaging Spring Boot Applications Efficient Deployments Efficient Deployments 默认情况下&#xff0c;基于SpringBoot框架开发应用时&#xff0c;构建插件spring-boot-maven-plugin将项目打包为fat jar。 执行如下命令&#xff0c;解压构建得到的jar文件。 java -Djarmo…

Python 程序设计基础教程

Python 程序设计基础教程 撰稿人&#xff1a;南星六月雪 第 一 章 变量与简单数据类型 1.1 变量 先来观察以下程序&#xff1a; world "Hello Python!" print(world)world "Hello Python,I love you!" print(world)运行这个程序&#xff0c;将看到两…

0827作业+梳理(c++day01)

一、作业&#xff1a; 1、代码 #include <iostream> using namespace std; int main() {string str;cout<<"请输入一个字符串"<<endl;getline(cin,str);cout<<"str "<<str<<endl;//初始化各类字符个数int size_num …

如何保证Redis与数据库之间的一致性

在现代应用程序架构中&#xff0c;Redis等内存数据库因其高性能和低延迟特性而被广泛用于缓存、会话管理、消息队列等多种场景。然而&#xff0c;当Redis作为数据库&#xff08;如MySQL、PostgreSQL&#xff09;的缓存层时&#xff0c;确保数据在Redis和数据库之间的一致性变得…

jmeter中CSV 数据文件设置用例

1、CSV数据文件的基础使用 线程组->添加->配置远近->CSV数据文件设置 2、多条用例运行CSV数据文件 由于我的csv请求的json数据有“&#xff0c;”所以我这边 分隔符选择了*号 写了两行需要测试的用例&#xff0c;需要添加一个“循环控制器” 线程组->添加-&g…

splunk Enterprise 的HTTP收集器-windows

1.创建HTTP收集器 2.使用HTTP收集器 然后打开全局设置&#xff1a;把ssl给去掉&#xff0c;点保存&#xff08;保存之后&#xff0c;可以看到这些状态全部都是已启用了&#xff09;&#xff1a; 3.测试&#xff1a; curl --location --request POST http://192.168.11.131:808…

List<String> 和 ArrayList<String>的区别

List<String> list new ArrayList<>() 这种形式实际上是一种向上转型&#xff08;upcasting&#xff09;的体现&#xff0c;ArrayList 实现了 List 接口&#xff0c;可以看成是从 List 继承而来&#xff0c;一个子类的对象可以指向它父类。 为什么不是 ArrayList…