数据的奇幻旅程:探索Python基础数据类型

目录

  • 写在开头
  • [1. 数字和运算符](#1. 数字和运算符)
    • [1.1 整数(int)和浮点数(float)](#1.1 整数(int)和浮点数(float))
    • [1.2 基本数学运算](#1.2 基本数学运算)
    • [1.3 取余和整除](#1.3 取余和整除)
    • [1.4 指数运算](#1.4 指数运算)
    • [1.5 数学函数](#1.5 数学函数)
    • [1.6 类型转换](#1.6 类型转换)
    • [1.7 复合赋值运算符](#1.7 复合赋值运算符)
    • [1.8 比较运算符](#1.8 比较运算符)
    • [1.9 逻辑运算符](#1.9 逻辑运算符)
      • [1.10 位运算](#1.10 位运算)
      • [1.11 `math` 模块](#1.11 math 模块)
      • [1.12 复数运算](#1.12 复数运算)
    • [1.13 数字格式化](#1.13 数字格式化)
      • [1.13.1 使用 `format()` 方法进行数字格式化输出](#1.13.1 使用 format() 方法进行数字格式化输出)
      • [1.13.2. 使用 f-字符串 进行数字格式化输出](#1.13.2. 使用 f-字符串 进行数字格式化输出)
      • [1.13.3 早期版本的用法(不建议)](#1.13.3 早期版本的用法(不建议))
      • [1.14 随机数生成](#1.14 随机数生成)
      • [1.15 十进制、二进制、八进制和十六进制表示](#1.15 十进制、二进制、八进制和十六进制表示)
      • [1.16 数学运算的异常处理](#1.16 数学运算的异常处理)
      • [1.17 `decimal` 模块](#1.17 decimal 模块)
      • [1.18 `fractions` 模块](#1.18 fractions 模块)
      • [1.19 `numpy` 库](#1.19 numpy 库)
      • [1.20 数学运算函数](#1.20 数学运算函数)
    • [1.21 四舍五入](#1.21 四舍五入)
      • [1.22 `sympy` 库](#1.22 sympy 库)
      • [1.23 大数运算](#1.23 大数运算)
      • [1.24 随机数生成和种子](#1.24 随机数生成和种子)
    • [2. 字符串和常用操作](#2. 字符串和常用操作)
      • [2.1. **字符串基本操作**](#2.1. 字符串基本操作)
      • [2.2. **字符串索引和切片**](#2.2. 字符串索引和切片)
      • [2.3. **字符串方法**](#2.3. 字符串方法)
      • [2.4. **格式化字符串**](#2.4. 格式化字符串)
      • [2.4.1 **字符串格式化方法 - `format()`**](#2.4.1 字符串格式化方法 - format())
      • [2.4.2 **f-字符串(Python 3.6+)**](#2.4.2 f-字符串(Python 3.6+))
      • [2.5. **字符串判断方法**](#2.5. 字符串判断方法)
      • [2.6. **字符串去除空格和特定字符**](#2.6. 字符串去除空格和特定字符)
      • [2.7. **字符串格式验证**](#2.7. 字符串格式验证)
      • [2.8. **字符串编码和解码**](#2.8. 字符串编码和解码)
      • [2.9. **字符串比较**](#2.9. 字符串比较)
      • [2.10. **字符串替换方法**](#2.10. 字符串替换方法)
      • [2.11. **字符串拆分与连接**](#2.11. 字符串拆分与连接)
      • [2.12. **字符串查找和计数**](#2.12. 字符串查找和计数)
      • [2.13. **字符串去除空格和特定字符**](#2.13. 字符串去除空格和特定字符)
      • [2.14. **字符串大小写转换**](#2.14. 字符串大小写转换)
      • [2.15. **字符串判断方法**](#2.15. 字符串判断方法)
  • 3.列表
    • [3.1 创建列表](#3.1 创建列表)
    • [3.2 列表索引和切片](#3.2 列表索引和切片)
    • [3.3 列表操作](#3.3 列表操作)
      • [3.3.1 添加元素](#3.3.1 添加元素)
      • [3.3.2 插入元素](#3.3.2 插入元素)
      • [3.3.3 删除元素](#3.3.3 删除元素)
    • [3.3.4 查找元素](#3.3.4 查找元素)
    • [3.3.5 计算元素个数](#3.3.5 计算元素个数)
    • [3.3.6 反转列表](#3.3.6 反转列表)
    • [3.3.7 排序列表](#3.3.7 排序列表)
    • [3.4 列表运算](#3.4 列表运算)
      • [3.4.1 连接列表](#3.4.1 连接列表)
      • [3.4.2 重复列表元素](#3.4.2 重复列表元素)
      • [3.4.3 成员资格检查](#3.4.3 成员资格检查)
      • [3.4.4 列表长度](#3.4.4 列表长度)
    • [3.5 列表的复制](#3.5 列表的复制)
    • [3.6 其他常见方法](#3.6 其他常见方法)
      • [3.6.1 清空列表](#3.6.1 清空列表)
      • [3.6.2 列表转字符串](#3.6.2 列表转字符串)
      • [3.6.3 `enumerate()`](#3.6.3 enumerate())
      • [3.6.4 `zip()`](#3.6.4 zip())
      • [3.6.5 使用 `filter()` 和 `map()`](#3.6.5 使用 filter()map())
      • [3.6.6 使用生成器表达式](#3.6.6 使用生成器表达式)
      • [3.6.7 使用 `any()` 和 `all()`](#3.6.7 使用 any()all())
      • [3.6.8 使用 `collections` 模块](#3.6.8 使用 collections 模块)
  • [4 字典(Dictionary)](#4 字典(Dictionary))
    • [4.1 创建字典](#4.1 创建字典)
      • [4.1.1 创建空字典](#4.1.1 创建空字典)
      • [4.1.2 创建带有键值对的字典](#4.1.2 创建带有键值对的字典)
      • [4.1.3 使用 `dict()` 构造函数创建字典](#4.1.3 使用 dict() 构造函数创建字典)
    • [4.2 访问和操作字典元素](#4.2 访问和操作字典元素)
      • [4.2.1 访问字典元素](#4.2.1 访问字典元素)
      • [4.2.2 添加/更新键值对](#4.2.2 添加/更新键值对)
      • [4.2.3 删除键值对](#4.2.3 删除键值对)
    • [4.3 字典方法](#4.3 字典方法)
      • [4.3.1 获取所有键和值](#4.3.1 获取所有键和值)
        • [4.3.1.1 获取所有键](#4.3.1.1 获取所有键)
        • [4.3.1.2 获取所有值](#4.3.1.2 获取所有值)
      • [4.3.2 获取键值对](#4.3.2 获取键值对)
      • [4.3.3 使用 `get()` 获取值](#4.3.3 使用 get() 获取值)
      • [4.3.4 使用 `setdefault()` 设置默认值](#4.3.4 使用 setdefault() 设置默认值)
      • [4.3.5 删除并获取元素](#4.3.5 删除并获取元素)
      • [4.3.6 清空字典](#4.3.6 清空字典)
    • [4.4 字典运算](#4.4 字典运算)
      • [4.4.1 复制字典](#4.4.1 复制字典)
        • [4.4.1.1 浅复制](#4.4.1.1 浅复制)
        • [4.4.1.2 深复制](#4.4.1.2 深复制)
      • [4.4.2 合并字典](#4.4.2 合并字典)
      • [4.4.3 使用字典解析式](#4.4.3 使用字典解析式)
    • [4.5 其他功能](#4.5 其他功能)
      • [4.5.1 检查键是否存在](#4.5.1 检查键是否存在)
      • [4.5.2 字典长度](#4.5.2 字典长度)
      • [4.5.3 弹出并删除最后一个插入的键值对](#4.5.3 弹出并删除最后一个插入的键值对)
      • [4.5.4 获取默认值](#4.5.4 获取默认值)
      • [4.5.5 使用 `fromkeys()` 创建字典](#4.5.5 使用 fromkeys() 创建字典)
      • [4.5.6 使用 `collections` 模块](#4.5.6 使用 collections 模块)
        • [4.5.6.1 计数器 (`Counter`)](#4.5.6.1 计数器 (Counter))
        • [4.5.6.2 默认字典 (`defaultdict`)](#4.5.6.2 默认字典 (defaultdict))
      • [4.5.7 使用 `filter()` 和 `map()`](#4.5.7 使用 filter()map())
      • [4.5.8 使用字典解析式](#4.5.8 使用字典解析式)
      • [4.5.9 使用 `any()` 和 `all()`](#4.5.9 使用 any()all())
  • [5 元组(Tuple)操作和运算方法](#5 元组(Tuple)操作和运算方法)
    • [5.1 创建元组](#5.1 创建元组)
      • [5.1.1 创建空元组](#5.1.1 创建空元组)
      • [5.1.2 创建包含元素的元组](#5.1.2 创建包含元素的元组)
      • [5.1.3 使用 `tuple()` 构造函数创建元组](#5.1.3 使用 tuple() 构造函数创建元组)
    • [5.2 访问和操作元组元素](#5.2 访问和操作元组元素)
      • [5.2.1 访问元组元素](#5.2.1 访问元组元素)
      • [5.2.2 切片](#5.2.2 切片)
    • [5.3 不可变性和元组特性](#5.3 不可变性和元组特性)
    • [5.4 元组方法](#5.4 元组方法)
      • [5.4.1 获取元组中元素的索引](#5.4.1 获取元组中元素的索引)
      • [5.4.2 统计元素出现的次数](#5.4.2 统计元素出现的次数)
    • [5.5 元组运算](#5.5 元组运算)
      • [5.5.1 连接元组](#5.5.1 连接元组)
      • [5.5.2 重复元组元素](#5.5.2 重复元组元素)
    • [5.6 扩展元组](#5.6 扩展元组)
      • [5.6.1 元组解包](#5.6.1 元组解包)
      • [5.6.2 链接元组和其他可迭代对象](#5.6.2 链接元组和其他可迭代对象)
    • [5.7 不可变性的优势](#5.7 不可变性的优势)
      • [5.7.1 元组作为字典的键](#5.7.1 元组作为字典的键)
      • [5.7.2 函数返回多个值](#5.7.2 函数返回多个值)
    • [5.8 使用 `enumerate()`](#5.8 使用 enumerate())
      • [5.8.1 `enumerate()`](#5.8.1 enumerate())
    • [5.9 使用 `zip()`](#5.9 使用 zip())
      • [5.9.1 `zip()`](#5.9.1 zip())
    • [5.10 使用生成器表达式](#5.10 使用生成器表达式)
      • [5.10.1 生成器表达式](#5.10.1 生成器表达式)
    • [5.11 使用 `any()` 和 `all()`](#5.11 使用 any()all())
      • [5.11.1 `any()` 和 `all()`](#5.11.1 any()all())
  • [6 集合(Set)操作和运算方法](#6 集合(Set)操作和运算方法)
    • [6.1 创建集合](#6.1 创建集合)
      • [6.1.1 创建空集合](#6.1.1 创建空集合)
      • [6.1.2 创建带有元素的集合](#6.1.2 创建带有元素的集合)
    • [6.2 添加和删除元素](#6.2 添加和删除元素)
      • [6.2.1 添加单个元素](#6.2.1 添加单个元素)
      • [6.2.2 添加多个元素](#6.2.2 添加多个元素)
      • [6.2.3 删除元素](#6.2.3 删除元素)
      • [6.2.4 安全删除元素](#6.2.4 安全删除元素)
      • [6.2.5 弹出元素](#6.2.5 弹出元素)
      • [6.2.6 清空集合](#6.2.6 清空集合)
    • [6.3 集合运算](#6.3 集合运算)
      • [6.3.1 并集](#6.3.1 并集)
      • [6.3.2 交集](#6.3.2 交集)
      • [6.3.3 差集](#6.3.3 差集)
      • [6.3.4 对称差集](#6.3.4 对称差集)
    • [6.4 集合方法](#6.4 集合方法)
      • [6.4.1 判断子集和超集](#6.4.1 判断子集和超集)
      • [6.4.2 判断相等性](#6.4.2 判断相等性)
      • [6.4.3 复制集合](#6.4.3 复制集合)
    • [6.5 集合推导式](#6.5 集合推导式)
      • [6.5.1 集合推导式](#6.5.1 集合推导式)
    • [6.6 使用 `filter()` 和 `map()`](#6.6 使用 filter()map())
      • [6.6.1 `filter()`](#6.6.1 filter())
      • [6.6.2 `map()`](#6.6.2 map())
    • [6.7 使用集合解析式](#6.7 使用集合解析式)
      • [6.7.1 集合解析式](#6.7.1 集合解析式)
    • [6.8 使用 `any()` 和 `all()`](#6.8 使用 any()all())
      • [6.8.1 `any()` 和 `all()`](#6.8.1 any()all())
  • 写在最后

写在开头

Python作为一门强大而灵活的编程语言,具有丰富的数据类型和灵活的变量赋值机制。本篇博客将深入介绍Python中的数据类型和变量,包括数字和运算符、字符串及其常用操作、列表、元组、集合,以及变量和赋值。

1. 数字和运算符

在Python中,数字包括整数和浮点数,而运算符则支持基本的加减乘除等操作。下面是一些常见的操作:

1.1 整数(int)和浮点数(float)

在Python中,数字主要分为整数和浮点数。整数是没有小数部分的数字,而浮点数包含小数部分。

python 复制代码
# 整数
integer_number = 42

# 浮点数
float_number = 3.14

1.2 基本数学运算

Python支持常见的基本数学运算,包括加法、减法、乘法和除法。

python 复制代码
# 加法
sum_result = 5 + 3

# 减法
difference_result = 7 - 2

# 乘法
product_result = 4 * 6

# 除法
division_result = 9 / 3

1.3 取余和整除

除了基本运算外,还有取余和整除的运算符。

python 复制代码
# 取余
remainder_result = 10 % 3

# 整除
integer_division_result = 20 // 3

1.4 指数运算

指数运算使用 ** 符号。

python 复制代码
# 指数运算
exponential_result = 2 ** 3

1.5 数学函数

Python内置了许多数学函数,例如绝对值、最大值、最小值等。

python 复制代码
# 绝对值
absolute_value = abs(-5)

# 最大值
max_value = max(3, 7, 1)

# 最小值
min_value = min(4, 2, 8)

1.6 类型转换

可以在不同数字类型之间进行转换,如整数转浮点数、浮点数转整数。

python 复制代码
# 整数转浮点数
float_conversion = float(7)

# 浮点数转整数
integer_conversion = int(3.14)

1.7 复合赋值运算符

复合赋值运算符可以简化赋值表达式,如 +=-=*=/=

python 复制代码
# 复合赋值
x = 5
x += 2  # 等同于 x = x + 2

1.8 比较运算符

比较运算符用于比较两个值,返回布尔值(True或False)。

python 复制代码
# 比较运算
is_equal = (10 == 5)
is_not_equal = (7 != 3)
greater_than = (8 > 5)
less_than_or_equal = (4 <= 6)

1.9 逻辑运算符

逻辑运算符用于组合多个条件,返回布尔值。

python 复制代码
# 逻辑运算
and_result = (True and False)
or_result = (True or False)
not_result = not True

1.10 位运算

Python也支持位运算,允许对整数的二进制位进行操作。

  • 按位与(Bitwise AND): & 运算符对两个数的每个对应位执行与操作。
  • 按位或(Bitwise OR): | 运算符对两个数的每个对应位执行或操作。
  • 按位异或(Bitwise XOR): ^ 运算符对两个数的每个对应位执行异或操作。
  • 按位取反(Bitwise NOT): ~ 运算符对数的每个位进行取反操作。
  • 左移(Left Shift): << 运算符将数字的位向左移动指定的位数。
  • 右移(Right Shift): >> 运算符将数字的位向右移动指定的位数。
python 复制代码
# 位运算示例
bitwise_and = 10 & 3
bitwise_or = 10 | 3
bitwise_xor = 10 ^ 3
bitwise_not = ~10
left_shift = 10 << 2
right_shift = 10 >> 2

1.11 math 模块

Python提供了内置的 math 模块,其中包含许多数学函数和常量。

python 复制代码
import math

# 平方根
square_root = math.sqrt(16)

# 对数
logarithm = math.log(100, 10)

# 三角函数
sin_value = math.sin(math.radians(90))  # sin(90度)

# 圆周率和常量
pi_value = math.pi
euler_constant = math.e

1.12 复数运算

Python也支持复数,可以进行复数的加减乘除等运算。

python 复制代码
# 复数运算
complex_number1 = 3 + 4j
complex_number2 = 1 - 2j

# 复数加法
complex_sum = complex_number1 + complex_number2

# 复数乘法
complex_product = complex_number1 * complex_number2

1.13 数字格式化

1.13.1 使用 format() 方法进行数字格式化输出

基本用法:

python 复制代码
number = 1234.56789
formatted_string = "{:.2f}".format(number)
print(formatted_string)
  • 输出结果:1234.57

格式化选项说明:

  • :f 表示浮点数格式。
  • .2 表示保留两位小数。

某些情况下我们可能需要用到以下形式的输出

python 复制代码
# 对齐与填充
formatted_string = "{:<10.2f}".format(number)  # 左对齐,总宽度为10,保留两位小数
print(formatted_string)  # 输出结果:`1234.57   `

# 千位分隔符
formatted_string = "{:,}".format(1234567)  # 添加千位分隔符
print(formatted_string)  # 输出结果:`1,234,567`

# 百分比格式
percentage = 0.75
formatted_string = "{:.2%}".format(percentage)  # 百分比格式,保留两位小数
print(formatted_string)  # 输出结果:`75.00%`

1.13.2. 使用 f-字符串 进行数字格式化输出

基本用法:

python 复制代码
number = 1234.56789
formatted_string = f"{number:.2f}"
print(formatted_string)
  • 输出结果:1234.57

格式化选项说明:

  • :f 表示浮点数格式。
  • .2 表示保留两位小数。

常用的输出方法:

python 复制代码
# 对齐与填充
formatted_string = f"{number:<10.2f}"  # 左对齐,总宽度为10,保留两位小数
print(formatted_string)  # 输出结果:`1234.57   `

# 千位分隔符
formatted_string = f"{1234567:,}"  # 添加千位分隔符
print(formatted_string)  # 输出结果:`1,234,567`

# 百分比格式
percentage = 0.75
formatted_string = f"{percentage:.2%}"  # 百分比格式,保留两位小数
print(formatted_string)  # 输出结果:`75.00%`

1.13.3 早期版本的用法(不建议)

老式的 % 操作符也可以用于数字格式化输出,但不如 format() 和 f-字符串那样灵活:

基本用法:
python 复制代码
number = 1234.56789
formatted_string = "%.2f" % number
print(formatted_string)
  • 输出结果:1234.57

常用输出:

python 复制代码
# 对齐与填充
formatted_string = "%-10.2f" % number  # 左对齐,总宽度为10,保留两位小数
print(formatted_string)  # 输出结果:`1234.57    `

# 千位分隔符
formatted_string = "{:,}".format(1234567)  # 添加千位分隔符
print(formatted_string)  # 输出结果:`1,234,567`

# 百分比格式
percentage = 0.75
formatted_string = "%.2f%%" % (percentage * 100)  # 百分比格式,保留两位小数
print(formatted_string)  # 输出结果:`75.00%`

虽然老式的 % 格式化方法仍然有效,但在新代码中,推荐使用 format() 方法或 f-字符串,因为它们提供了更多的功能和更清晰的语法。老式 % 操作符在未来可能会被淘汰。

1.14 随机数生成

Python的 random 模块提供了生成随机数的功能,包括生成随机整数、随机浮点数等。

python 复制代码
import random

# 生成随机整数
random_integer = random.randint(1, 10)

# 生成随机浮点数
random_float = random.uniform(0, 1)

1.15 十进制、二进制、八进制和十六进制表示

在Python中,可以使用不同的前缀来表示数字的不同进制。

python 复制代码
# 十进制
decimal_number = 42

# 二进制,以0b为前缀
binary_number = 0b101010

# 八进制,以0o为前缀
octal_number = 0o52

# 十六进制,以0x为前缀
hexadecimal_number = 0x2A

1.16 数学运算的异常处理

在进行数学运算时,可能会遇到除零错误(ZeroDivisionError)等异常。使用异常处理机制可以增加程序的稳定性。

python 复制代码
try:
    result = 10 / 0
except ZeroDivisionError as e:
    result = "Error: Division by zero"
    print(e)

1.17 decimal 模块

对于需要高精度计算的场景,Python提供了 decimal 模块。

python 复制代码
from decimal import Decimal, getcontext

# 设置精度
getcontext().prec = 4

# 使用 Decimal 类进行高精度计算
result = Decimal('1') / Decimal('3')

1.18 fractions 模块

fractions 模块用于处理有理数。

python 复制代码
from fractions import Fraction

# 创建有理数
fraction_result = Fraction(4, 3)

1.19 numpy

对于科学计算和数组操作,常常使用 numpy 库。

python 复制代码
import numpy as np

# 创建数组
array = np.array([1, 2, 3, 4, 5])

# 数组运算
sum_array = np.sum(array)

1.20 数学运算函数

Python的 math 模块提供了许多常用的数学函数,涵盖了三角函数、指数函数、对数函数等。

python 复制代码
import math

# 三角函数
sin_value = math.sin(math.radians(45))  # sin(45度)

# 指数函数
exp_value = math.exp(2)  # e^2

# 对数函数
log_value = math.log(10, 2)  # 以2为底的对数

1.21 四舍五入

使用内置函数 round() 可以进行四舍五入。

python 复制代码
# 四舍五入
rounded_value = round(3.14159, 2)  # 保留两位小数

1.22 sympy

对于符号运算,可以使用 sympy 库。

python 复制代码
from sympy import symbols, simplify

# 定义符号
x, y = symbols('x y')

# 符号表达式
expression = x**2 + 2*x + 1

# 简化表达式
simplified_expression = simplify(expression)

1.23 大数运算

对于超出普通整数范围的大数运算,可以使用 int 类型的无限精度。

python 复制代码
big_integer = 10**100

1.24 随机数生成和种子

random 模块提供了伪随机数生成,可以使用 seed() 函数设置随机数生成的种子。

python 复制代码
import random

# 设置随机数种子
random.seed(42)

# 生成随机整数
random_number = random.randint(1, 10)

这些进一步扩展了数字和运算在Python中的应用范围,涵盖了复数、数学函数、大数运算、符号运算以及随机数生成等更加复杂和高级的主题。

2. 字符串和常用操作

Python 中字符串是不可变(immutable)的序列,因此有许多内建的方法和运算符来进行字符串的操作和处理。下面是一些常用的字符串操作和运算方法

2.1. 字符串基本操作

创建字符串:

python 复制代码
str1 = "Hello, "
str2 = 'World!'

字符串拼接:

python 复制代码
result = str1 + str2
print(result)  # 输出结果:**`Hello, World!`

复制字符串:

python 复制代码
str_copy = str1 * 3
print(str_copy)  # 输出结果:**`Hello, Hello, Hello, `

获取字符串长度:

python 复制代码
length = len(str1)
print(length)  # 输出结果:**`7`

2.2. 字符串索引和切片

字符串索引:

python 复制代码
first_char = str1[0]  # 获取第一个字符
print(first_char)  # 输出结果:**`H`

字符串切片:

python 复制代码
substring = str1[0:5]  # 获取索引0到4的子字符串
print(substring)  # 输出结果:**`Hello`

2.3. 字符串方法

转换为大写和小写:

python 复制代码
upper_str = str1.upper()
lower_str = str2.lower()
print(upper_str)  # 输出结果:**`HELLO, `
print(lower_str)  # 输出结果:**`world!`

查找子字符串:

python 复制代码
index = str1.find('l')  # 查找第一个 'l' 的索引
print(index)  # 输出结果:**`2`

替换子字符串:

python 复制代码
new_str = str1.replace('l', 'L')
print(new_str)  # 输出结果:**`HeLLo, `

分割字符串:

python 复制代码
words = str1.split(', ')
print(words)  # 输出结果:**`['Hello', 'World!']`

连接字符串列表:

python 复制代码
joined_str = '-'.join(words)
print(joined_str)  # 输出结果:**`Hello-World!`

2.4. 格式化字符串

2.4.1 字符串格式化方法 - format()

基本用法:

python 复制代码
name = "Alice"
age = 30
formatted_str = "My name is {} and I am {} years old.".format(name, age)
print(formatted_str)
# 输出结果:**`My name is Alice and I am 30 years old.`

位置参数和关键字参数:

python 复制代码
formatted_str = "My name is {0} and I am {1} years old. I live in {city}.".format("Bob", 25, city="Wonderland")
print(formatted_str)
# 输出结果:**`My name is Bob and I am 25 years old. I live in Wonderland.`

格式化选项:

python 复制代码
pi = 3.141592653589793
formatted_str = "The value of pi is approximately {:.2f}".format(pi)
print(formatted_str)
# 输出结果:**`The value of pi is approximately 3.14`

2.4.2 f-字符串(Python 3.6+)

基本用法:

python 复制代码
name = "Charlie"
age = 22
formatted_str = f"My name is {name} and I am {age} years old."
print(formatted_str)
# 输出结果:**`My name is Charlie and I am 22 years old.`

表达式和函数调用:

python 复制代码
x = 5
formatted_str = f"The square of {x} is {x**2}."
print(formatted_str)
# 输出结果:**`The square of 5 is 25.`

格式化选项:

python 复制代码
pi = 3.141592653589793
formatted_str = f"The value of pi is approximately {pi:.2f}"
print(formatted_str)
# 输出结果:**`The value of pi is approximately 3.14`

使用 f-字符串(Python 3.6+):

python 复制代码
name = "Bob"
age = 30
greeting = f"Hello, {name}! You are {age} years old."
print(greeting)
# 输出结果:**`Hello, Bob! You are 30 years old.`

2.5. 字符串判断方法

判断字符串开头和结尾:

python 复制代码
text = "Hello, World!"
starts_with_hello = text.startswith("Hello")
ends_with_world = text.endswith("World!")
print(starts_with_hello)  # 输出结果:**`True`
print(ends_with_world)   # 输出结果:**`True`

判断字符串是否全是字母或数字:

python 复制代码
alpha_check = text.isalpha()  # 是否全是字母
numeric_check = text.isdigit()  # 是否全是数字
print(alpha_check)  # 输出结果:**`False`
print(numeric_check)  # 输出结果:**`False`

2.6. 字符串去除空格和特定字符

移除字符串两端的空格:

python 复制代码
whitespace_text = "   Python is fun!   "
stripped_text = whitespace_text.strip()
print(stripped_text)  # 输出结果:**`Python is fun!`

移除字符串中的特定字符:

python 复制代码
original_text = "Hello, Python!"
removed_comma_text = original_text.replace(',', '')
print(removed_comma_text)  # 输出结果:**`Hello Python!`

2.7. 字符串格式验证

判断字符串是否为邮箱地址:

python 复制代码
email = "user@example.com"
is_email = '@' in email and '.' in email.split('@')[1]
print(is_email)  # 输出结果:**`True`

判断字符串是否为整数或浮点数:

python 复制代码
num_str = "123.45"
is_integer = num_str.isdigit()  # 是否为整数
is_float = '.' in num_str and num_str.replace('.', '', 1).isdigit()  # 是否为浮点数
print(is_integer)  # 输出结果:**`False`
print(is_float)    # 输出结果:**`True`

2.8. 字符串编码和解码

编码为字节串:

python 复制代码
unicode_str = "你好"
encoded_str = unicode_str.encode('utf-8')
print(encoded_str)  # 输出结果:**`b'\xe4\xbd\xa0\xe5\xa5\xbd'`

解码字节串:

python 复制代码
decoded_str = encoded_str.decode('utf-8')
print(decoded_str)  # 输出结果:**`你好`

2.9. 字符串比较

字符串比较:

python 复制代码
str1 = "apple"
str2 = "banana"
comparison_result = str1 < str2  # 字典序比较
print(comparison_result)  # 输出结果:**`True`

2.10. 字符串替换方法

str.replace() 方法:

python 复制代码
original_text = "Python is fun, Python is powerful."
new_text = original_text.replace("Python", "JavaScript")
print(new_text)
# 输出结果:**`JavaScript is fun, JavaScript is powerful.`

使用正则表达式进行替换:

python 复制代码
import re

pattern = re.compile(r'\bPython\b', re.IGNORECASE)  # 忽略大小写
new_text = pattern.sub('JavaScript', original_text)
print(new_text)
# 输出结果:**`JavaScript is fun, JavaScript is powerful.`

2.11. 字符串拆分与连接

str.split() 方法:

python 复制代码
sentence = "This is a beautiful day"
words = sentence.split()
print(words)
# 输出结果:**`['This', 'is', 'a', 'beautiful', 'day']`

指定分隔符拆分:

python 复制代码
csv_data = "apple,orange,banana,grape"
fruits = csv_data.split(',')
print(fruits)
# 输出结果:**`['apple', 'orange', 'banana', 'grape']`

使用 str.join() 连接字符串:

python 复制代码
joined_sentence = ' '.join(words)
print(joined_sentence)
# 输出结果:**`This is a beautiful day`

2.12. 字符串查找和计数

str.find() 方法:

python 复制代码
sentence = "Python programming is fun and Pythonic"
index = sentence.find("Python")
print(index)
# 输出结果:**`0`

str.count() 方法:

python 复制代码
count_python = sentence.count("Python")
print(count_python)
# 输出结果:**`2`

2.13. 字符串去除空格和特定字符

str.strip() 方法:

python 复制代码
whitespace_text = "   Python is fun!   "
stripped_text = whitespace_text.strip()
print(stripped_text)
# 输出结果:**`Python is fun!`

去除特定字符:

python 复制代码
original_text = "Hello, Python!"
removed_comma_text = original_text.replace(',', '')
print(removed_comma_text)
# 输出结果:**`Hello Python!`

2.14. 字符串大小写转换

转为大写:

python 复制代码
text = "python programming"
uppercase_text = text.upper()
print(uppercase_text)
# 输出结果:**`PYTHON PROGRAMMING`

转为小写:

python 复制代码
uppercase_text = text.lower()
print(uppercase_text)
# 输出结果:**`python programming`

首字母大写:

python 复制代码
text = "hello, world!"
capitalized_text = text.capitalize()
print(capitalized_text)
# 输出结果:**`Hello, world!`

每个单词的首字母大写:

python 复制代码
text = "python programming is awesome"
titlecased_text = text.title()
print(titlecased_text)
# 输出结果:**`Python Programming Is Awesome`

2.15. 字符串判断方法

判断字符串是否以指定子字符串开头:

python 复制代码
text = "Python is powerful"
startswith_python = text.startswith("Python")
print(startswith_python)
# 输出结果:**`True`

判断字符串是否以指定子字符串结尾:

python 复制代码
endswith_powerful = text.endswith("powerful")
print(endswith_powerful)
# 输出结果:**`True`

判断字符串是否全是字母或数字:

python 复制代码
alpha_check = text.isalpha()  # 是否全是字母
numeric_check = text.isdigit()  # 是否全是数字
print(alpha_check)  # 输出结果:**`False`
print(numeric_check)  # 输出结果:**`False`

判断字符串是否全是空格字符:

python 复制代码
whitespace_check = text.isspace()
print(whitespace_check)
# 输出结果:**`False`

3.列表

3.1 创建列表

创建空列表

python 复制代码
my_list = []

创建带有元素的列表

python 复制代码
my_list = [1, 2, 3, 4, 5]

使用range创建列表

python 复制代码
my_list = list(range(1, 6))

使用列表解析

使用列表解析可以简洁地创建新列表。

python 复制代码
squared_numbers = [x**2 for x in my_list]

3.2 列表索引和切片

访问列表元素

python 复制代码
first_element = my_list[0]  # 获取第一个元素

使用负索引

python 复制代码
last_element = my_list[-1]  # 获取最后一个元素

使用切片

python 复制代码
subset = my_list[1:4]  # 获取索引1到3的子列表

3.3 列表操作

3.3.1 添加元素

a. append()

python 复制代码
my_list.append(6)  # 在列表末尾添加元素

b. extend()

python 复制代码
my_list.extend([7, 8, 9])  # 在列表末尾添加多个元素

3.3.2 插入元素

python 复制代码
my_list.insert(2, 10)  # 在索引2的位置插入元素10

3.3.3 删除元素

a. remove()

python 复制代码
my_list.remove(3)  # 删除第一个值为3的元素

b. pop()

python 复制代码
removed_element = my_list.pop(2)  # 删除索引2的元素并返回该元素

3.3.4 查找元素

python 复制代码
index_of_element = my_list.index(4)  # 返回值为4的元素的索引

3.3.5 计算元素个数

python 复制代码
count_of_element = my_list.count(2)  # 返回值为2的元素在列表中出现的次数

3.3.6 反转列表

python 复制代码
my_list.reverse()  # 反转列表中的元素顺序

3.3.7 排序列表

a. sort()

python 复制代码
my_list.sort()  # 升序排序

b. sorted()

python 复制代码
sorted_list = sorted(my_list, reverse=True)  # 降序排序,返回新列表

3.4 列表运算

3.4.1 连接列表

python 复制代码
combined_list = my_list + [11, 12, 13]

3.4.2 重复列表元素

python 复制代码
repeated_list = my_list * 2

3.4.3 成员资格检查

python 复制代码
is_present = 5 in my_list  # 检查值5是否在列表中

3.4.4 列表长度

python 复制代码
length_of_list = len(my_list)  # 返回列表的长度

3.5 列表的复制

浅复制

python 复制代码
new_list = my_list.copy()  # 或者使用 new_list = my_list[:]

深复制

python 复制代码
import copy
deep_copy = copy.deepcopy(my_list)

3.6 其他常见方法

3.6.1 清空列表

python 复制代码
my_list.clear()  # 清空列表

3.6.2 列表转字符串

python 复制代码
list_as_string = ', '.join(map(str, my_list))

3.6.3 enumerate()

enumerate() 函数用于同时获取索引和元素。

python 复制代码
for index, value in enumerate(my_list):
    print(f"Index: {index}, Value: {value}")

3.6.4 zip()

zip() 函数用于将两个列表组合成一个元组的列表。

python 复制代码
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped_list = list(zip(list1, list2))

3.6.5 使用 filter()map()

filter()

filter() 函数用于过滤列表中的元素。

python 复制代码
even_numbers = list(filter(lambda x: x % 2 == 0, my_list))

map()

map() 函数用于对列表中的每个元素执行相同的操作。

python 复制代码
squared_numbers = list(map(lambda x: x**2, my_list))

3.6.6 使用生成器表达式

生成器表达式是一种创建生成器的紧凑语法。

python 复制代码
squared_numbers_generator = (x**2 for x in my_list)

3.6.7 使用 any()all()

any()all()

any() 函数用于检查列表中是否至少有一个 True,而 all() 函数用于检查列表中是否所有元素都是 True

python 复制代码
has_positive = any(x > 0 for x in my_list)
all_positive = all(x > 0 for x in my_list)

3.6.8 使用 collections 模块

计数器 (Counter)

Countercollections 模块中的一个类,用于计算可迭代对象中元素的数量。

python 复制代码
from collections import Counter

element_counts = Counter(my_list)

4 字典(Dictionary)

4.1 创建字典

4.1.1 创建空字典

python 复制代码
my_dict = {}

4.1.2 创建带有键值对的字典

python 复制代码
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

4.1.3 使用 dict() 构造函数创建字典

python 复制代码
my_dict = dict(name='John', age=25, city='New York')

4.2 访问和操作字典元素

4.2.1 访问字典元素

python 复制代码
name_value = my_dict['name']
name_value = my_dict.get('name')

4.2.2 添加/更新键值对

python 复制代码
my_dict['gender'] = 'Male'  # 添加新键值对
my_dict['age'] = 26  # 更新现有键的值

4.2.3 删除键值对

python 复制代码
del my_dict['city']  # 删除指定键值对

4.3 字典方法

4.3.1 获取所有键和值

4.3.1.1 获取所有键
python 复制代码
keys = my_dict.keys()
4.3.1.2 获取所有值
python 复制代码
values = my_dict.values()

4.3.2 获取键值对

python 复制代码
items = my_dict.items()

4.3.3 使用 get() 获取值

python 复制代码
age_value = my_dict.get('age', 0)  # 如果键不存在,返回默认值0

4.3.4 使用 setdefault() 设置默认值

python 复制代码
my_dict.setdefault('gender', 'Unknown')  # 如果键不存在,设置默认值

4.3.5 删除并获取元素

python 复制代码
removed_value = my_dict.pop('age')  # 删除键值对并返回值

4.3.6 清空字典

python 复制代码
my_dict.clear()

4.4 字典运算

4.4.1 复制字典

4.4.1.1 浅复制
python 复制代码
new_dict = my_dict.copy()
4.4.1.2 深复制
python 复制代码
import copy
deep_copy = copy.deepcopy(my_dict)

4.4.2 合并字典

python 复制代码
other_dict = {'country': 'USA', 'language': 'English'}
my_dict.update(other_dict)  # 合并字典

4.4.3 使用字典解析式

python 复制代码
squared_numbers = {x: x**2 for x in range(1, 6)}

4.5 其他功能

4.5.1 检查键是否存在

python 复制代码
key_exists = 'name' in my_dict

4.5.2 字典长度

python 复制代码
length_of_dict = len(my_dict)

4.5.3 弹出并删除最后一个插入的键值对

python 复制代码
last_item = my_dict.popitem()

4.5.4 获取默认值

python 复制代码
default_value = my_dict.setdefault('country', 'Unknown')

4.5.5 使用 fromkeys() 创建字典

python 复制代码
keys = ['name', 'age', 'city']
default_dict = dict.fromkeys(keys, 'Unknown')

4.5.6 使用 collections 模块

4.5.6.1 计数器 (Counter)

Countercollections 模块中的一个类,用于计算可迭代对象中元素的数量。

python 复制代码
from collections import Counter

element_counts = Counter(my_dict)
4.5.6.2 默认字典 (defaultdict)

defaultdictcollections 模块中的一个类,它创建一个字典,其中缺失的键具有默认值。

python 复制代码
from collections import defaultdict

default_dict = defaultdict(int)
for key in my_dict:
    default_dict[key] = my_dict[key]

4.5.7 使用 filter()map()

使用filter()

filter() 函数用于过滤字典中的元素。

python 复制代码
filtered_dict = {k: v for k, v in my_dict.items() if v > 25}

使用map()

map() 函数用于对字典中的值执行相同的操作。

python 复制代码
mapped_dict = {k: v**2 for k, v in my_dict.items()}

4.5.8 使用字典解析式

字典解析式

使用字典解析式可以快速创建新字典。

python 复制代码
squared_numbers = {x: x**2 for x in range(1, 6)}

4.5.9 使用 any()all()

any()all()

any() 函数用于检查字典中是否至少有一个 True,而 all() 函数用于检查字典中是否所有值都是 True

python 复制代码
has_positive_age = any(age > 0 for age in my_dict.values())
all_ages_positive = all(age > 0 for age in my_dict.values())

5 元组(Tuple)操作和运算方法

5.1 创建元组

5.1.1 创建空元组

python 复制代码
my_tuple = ()

5.1.2 创建包含元素的元组

python 复制代码
my_tuple = (1, 2, 3, 4, 5)

5.1.3 使用 tuple() 构造函数创建元组

python 复制代码
my_tuple = tuple([1, 2, 3, 4, 5])

5.2 访问和操作元组元素

5.2.1 访问元组元素

python 复制代码
first_element = my_tuple[0]

5.2.2 切片

python 复制代码
subset = my_tuple[1:4]

5.3 不可变性和元组特性

元组的不可变性

python 复制代码
# 尝试修改元组元素将引发错误
my_tuple[0] = 10

5.4 元组方法

5.4.1 获取元组中元素的索引

python 复制代码
index_of_3 = my_tuple.index(3)

5.4.2 统计元素出现的次数

python 复制代码
count_of_2 = my_tuple.count(2)

5.5 元组运算

5.5.1 连接元组

python 复制代码
combined_tuple = my_tuple + (6, 7, 8)

5.5.2 重复元组元素

python 复制代码
repeated_tuple = my_tuple * 2

5.6 扩展元组

5.6.1 元组解包

python 复制代码
a, b, c = my_tuple

5.6.2 链接元组和其他可迭代对象

python 复制代码
extended_tuple = my_tuple + tuple([6, 7, 8])

5.7 不可变性的优势

5.7.1 元组作为字典的键

python 复制代码
my_dict = {(1, 2): 'value', (3, 4): 'another value'}

5.7.2 函数返回多个值

python 复制代码
def return_multiple_values():
    return 1, 2, 3

result = return_multiple_values()

5.8 使用 enumerate()

5.8.1 enumerate()

enumerate() 函数用于同时获取索引和元素。

python 复制代码
for index, value in enumerate(my_tuple):
    print(f"Index: {index}, Value: {value}")

5.9 使用 zip()

5.9.1 zip()

zip() 函数用于将两个元组组合成一个元组的列表。

python 复制代码
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
zipped_tuple = tuple(zip(tuple1, tuple2))

5.10 使用生成器表达式

5.10.1 生成器表达式

生成器表达式是一种创建生成器的紧凑语法。

python 复制代码
squared_numbers_generator = (x**2 for x in my_tuple)

5.11 使用 any()all()

5.11.1 any()all()

any() 函数用于检查元组中是否至少有一个 True,而 all() 函数用于检查元组中是否所有元素都是 True

python 复制代码
has_positive = any(x > 0 for x in my_tuple)
all_positive = all(x > 0 for x in my_tuple)

在处理大型数据集或需要更高效的操作时,这些方法可能会更有优势。

6 集合(Set)操作和运算方法

6.1 创建集合

6.1.1 创建空集合

python 复制代码
my_set = set()

6.1.2 创建带有元素的集合

python 复制代码
my_set = {1, 2, 3, 4, 5}

6.2 添加和删除元素

6.2.1 添加单个元素

python 复制代码
my_set.add(6)

6.2.2 添加多个元素

python 复制代码
my_set.update({7, 8, 9})

6.2.3 删除元素

python 复制代码
my_set.remove(3)

6.2.4 安全删除元素

python 复制代码
my_set.discard(10)

6.2.5 弹出元素

python 复制代码
popped_element = my_set.pop()

6.2.6 清空集合

python 复制代码
my_set.clear()

6.3 集合运算

6.3.1 并集

python 复制代码
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
union_set = set1 | set2
# 或者
union_set = set1.union(set2)

6.3.2 交集

python 复制代码
intersection_set = set1 & set2
# 或者
intersection_set = set1.intersection(set2)

6.3.3 差集

python 复制代码
difference_set = set1 - set2
# 或者
difference_set = set1.difference(set2)

6.3.4 对称差集

python 复制代码
symmetric_difference_set = set1 ^ set2
# 或者
symmetric_difference_set = set1.symmetric_difference(set2)

6.4 集合方法

6.4.1 判断子集和超集

python 复制代码
is_subset = set1.issubset(set2)
is_superset = set1.issuperset(set2)

6.4.2 判断相等性

python 复制代码
is_equal = set1 == set2

6.4.3 复制集合

python 复制代码
new_set = set1.copy()

6.5 集合推导式

6.5.1 集合推导式

python 复制代码
squared_set = {x**2 for x in range(1, 6)}

6.6 使用 filter()map()

6.6.1 filter()

filter() 函数用于过滤集合中的元素。

python 复制代码
filtered_set = set(filter(lambda x: x % 2 == 0, my_set))

6.6.2 map()

map() 函数用于对集合中的每个元素执行相同的操作。

python 复制代码
squared_set = set(map(lambda x: x**2, my_set))

6.7 使用集合解析式

6.7.1 集合解析式

使用集合解析式可以快速创建新集合。

python 复制代码
even_squares_set = {x**2 for x in range(1, 6) if x % 2 == 0}

6.8 使用 any()all()

6.8.1 any()all()

any() 函数用于检查集合中是否至少有一个 True,而 all() 函数用于检查集合中是否所有元素都是 True

python 复制代码
has_positive = any(x > 0 for x in my_set)
all_positive = all(x > 0 for x in my_set)

这些方法提供了更高级的集合操作和功能,可以根据需求选择使用。在处理数据唯一性或进行集合运算时,这些方法可能会更有优势。

写在最后

深入理解这些理论知识,我们可以更好地利用Python中数据类型和变量的特性,写出更加高效、清晰和可维护的代码。这些知识将为我们在实际项目中处理复杂问题提供强大的工具,祝您旅途愉快~

相关推荐
SiYuanFeng17 小时前
Colab复现 NanoChat:从 Tokenizer(CPU)、Base Train(CPU) 到 SFT(GPU) 的完整踩坑实录
python·colab
炸炸鱼.17 小时前
Python 操作 MySQL 数据库
android·数据库·python·adb
_深海凉_18 小时前
LeetCode热题100-颜色分类
python·算法·leetcode
AC赳赳老秦19 小时前
OpenClaw email技能:批量发送邮件、自动回复,高效处理工作邮件
运维·人工智能·python·django·自动化·deepseek·openclaw
zhaoshuzhaoshu19 小时前
Python 语法之数据结构详细解析
python
AI问答工程师19 小时前
Meta Muse Spark 的"思维压缩"到底是什么?我用 Python 复现了核心思路(附代码)
人工智能·python
zfan52020 小时前
python对Excel数据处理(1)
python·excel·pandas
小饕20 小时前
我从零搭建 RAG 学到的 10 件事
python
老歌老听老掉牙20 小时前
PyQt5+Qt Designer实战:可视化设计智能参数配置界面,告别手动布局时代!
python·qt
格鸰爱童话21 小时前
向AI学习项目技能(六)
java·人工智能·spring boot·python·学习