Python笔记

学习Python编程的利器

  • Python官方文档 https://www.python.org/doc/

  • iPython https://www.ipython.org/

  • Jupyter notebook http://jpyter.notebook.readthedocs.io/en/latest/

  • sublime text https://www.sublimetext.com

  • PyCharm https://www.jetbrains.com/pycharm/

  • Pip https://pip.pypa.io/en/stable/installing/

    # 安装命令
    curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
    

基础数据类型

数据类型

  • 整数 int 8
  • 浮点数 float 8.8
  • 字符串 str “8” “python”
  • 布尔值 bool True False

序列

指它的成员都是有序排列,并且可以通过下标偏移量访问到它的一个或多个成员。

  • 字符串 “abcd”

  • 列表 [0, “abcd”] 内容可变更

  • 元组 (“abc”, “def”) 内容不可变更

    列表与元组的区别:列表可以增减数据。 append增加,remove 移除

序列的基本操作

  • 成员关系操作符 in、 not in

    对象 [not] in 序列
    
  • 连接操作符 +

    序列 + 序列
    
  • 重复操作符 *

    序列 * 整数
    
  • 切片操作符 :

    序列[0:整数]
    
mothoh_day=(3,22)
zooiac_day=filter(lambda x:x<=mothoh_day,zooiac_days)
print(zooiac_day)
zooiac_day_list=list(zooiac_day)
print(zooiac_day_list)
zooiac_len=len(zooiac_day_list)
print(zooiac_len)
shengxiao=zooiac_name[zooiac_len%12]
print(shengxiao)

##
<filter object at 0x10346b340>
[(1, 20), (2, 19), (3, 21)]
3
白羊座

循环语句

for

注意: print 输出变量和字符串一起时,需要注意替换

for 迭代变量 in 可迭代对象:
代码块

print('%s 您好,今年是 %s 年' % (year, zooiac))
print("num %s" % num)

while

while 表达式:
	代码块
  
break 跳出代码块
continue 跳过当前代码
if i == 5:
  continue

映射类型:字典

{“哈希值”,“对象”}

{‘length’:180,‘width’:80}

# 声明一个字典
dict = {}
print(type(dict))
dict2 = {'x':1,'y':2}
print(dict2)
# 增加新值
dict2['z'] = 3
print(dict2)

列表推导式与字典推导式

# 计算从1到10所有偶数的平方
# 列表
alist = []
for i in range(1, 11):
    if i % 2 == 0:
        alist.append(i)
        print(alist)

blist=[i * i for i in range(10) if (i % 2) == 0]
print(blist)
# 计算从1到10所有偶数的平方
# 字典
z = {}
for i in blist:
    z[i] = 0
print(z)

z = {i:0 for i in blist}
print(i)

$ {0: 0, 4: 0, 16: 0, 36: 0, 64: 0}

函数

文件的内建函数

  • open() 打开文件

  • read() 输入

  • readline() 输入一行

  • seek() 文件内移动

  • write() 输出

  • close() 关闭文件

# 输入文件内容
file1 = open("name.txt", "w", encoding="utf-8")
file1.write("诸葛亮")
file1.write("黄月英")
file1.close()

# 输出文件内容
file2 = open("name.txt", encoding="utf-8")
print(file2.read())
file2.close()

# 输出文件内容的一行 readline()
file3 = open("name.txt", encoding="utf-8")
print(file1.readline())
file3.close()

# 逐行输出
file4 = open("name.txt", encoding="utf-8")
for line in file4.readlines():
    print(line)
    
# 移动指针位置
file5 = open("name.txt", encoding="utf-8")
print(file5.tell()) # 输出指针位置
print(file5.read(1))
print(file5.read(2))
print(file5.tell()) # 输出指针位置
file5.seek(0)
print(file5.tell()) # 输出指针位置
file5.close()

异常的检测和处理

异常不等于错误,异常是出现错误时采用正常控制流以外的动作。

异常处理的一般流程是: 检测到错误,引发异常;对异常进行捕获的操作。

try:
    <监控异常>
except Exception[,reason]:
#except Exception as e:
    <异常处理代码>
finally:
    <无论异常是否发生都执行>

函数的定义和常用操作

函数是对程序逻辑进行结构化的一种编程方法

# 函数的定义
def 函数名称():
    todo
    return 需要返回的内容

# 函数的调用
函数名称()
import re
# 统计文本中某些字段出现的次数

# 定义一个读取文件统计出现次数的函数
def find_item(char_name):
    with open("sanguo.txt", encoding="utf-8") as f:
        data = f.read().replace("\n", "")
        char_num = re.findall(char_name, data)
    return char_name, len(char_num)

# 读取人物信息
name_dict = {}
with open("name.txt", encoding="utf-8") as f:
    for line in f:
        names = line.split("|")
        for name in names:
            char_name, char_number = find_item(name)
            name_dict[char_name] = char_number

# 读取地名信息
diming_dict = {}
with open("diming.txt", encoding="utf-8") as f:
    i = 1
    for line in f:
        if i % 2 == 1:
            dingming_name, diming_number = find_item(line.strip())
            diming_dict[dingming_name] = diming_number
        i = i + 1

diming_sorted = sorted(diming_dict.items(), key=lambda x: x[1], reverse=True)
print(diming_sorted[0:10])

name_sorted = sorted(name_dict.items(), key=lambda x: x[1], reverse=True)
print(name_sorted[0:10])

可变长参数

# *other, 在参数前添加 *
def howlang(a *other):
    print (1 + len(other))
howlang(1 2 3)
$ 3

函数的变量作用域

使用 global 将函数中的变量变成全局变量,不使用 global,变量只在函数内部生效

var1 = 123
def func():
    global var1
    var1 = 234
    print(var1)
func()
print(var1) 
$ 234
$ 234

函数的迭代器与生成器

迭代器

iter 与 next

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
it = iter(list1)
print(next(it))
print(next(it))

生成器

yield

# 自己构建迭代器的时候,使用 yield,如果不使用 yield,则会一次性输出,使用后则会迭代输出
def frange(start, stop, step):
    i = start
    while i <= stop:
        yield i
        i += step

for i in frange(1, 10, 0.5):
    print(i)

lambda 表达式

需要掌握正写与反写

def ture():
    return True
lambda: True

def add(x, y):
    return x + y
lambda x, y: x + y

lambda x: x <= (month, day)
def func1(x):
    return x <= (month, day)

lambda item:item[1]
def func2(item):
    return item[1]

Python的内建函数

filter map reduce zip

# filter(function, iterable, /)
a = [1, 2, 3, 4, 5]
print(list(filter(lambda x: x % 2 == 0, a)))
$ [2, 4]
# map(function, iterable, /, *iterables)
a = [1, 2, 3, 4, 5]
# print(list(filter(lambda x: x % 2 == 0, a)))
b = [2, 3, 4, 5, 6]
print(list(map(lambda x: x + 1, a)))
print(list(map(lambda x, y: x + y, a, b)))
$ [2, 3, 4, 5, 6]
$ [3, 5, 7, 9, 11]
# reduce虽然是内建函数,但是需要执行命令导入
from functools import reduce
# reduce(function, iterable[, initial], /) -> value
>>> reduce(lambda x,y: x+y, [1,2,3],1)
7
# ((1+1)+2)+3=7
# zip(*iterables, strict=False)

>>> for i in zip((1,2,3),(4,5,6)):
...     print(i)
...     
(1, 4)
(2, 5)
(3, 6)

>>> dict1={"a":"aa","b":"bb"}
>>> dict2=zip(dict1.values(),dict1.keys())
>>> print(dict(dict2))
{'aa': 'a', 'bb': 'b'}

闭包

外部函数的变量被内部的函数引用,则叫做闭包。return 返回内部函数名称,不要()

def add():
    num1=1
    num2=2
    return num1+num2

def add1(a):
    def add2(b):
        return a+b
    return add2

print(add())
sum=add1(1)
# 注意此处使用sum()调用
print(sum(2))
$ 3
$ 3

装饰器

def timmer(func):
    def wrapper():
        start = time.time()
        func()
        end = time.time()
        print("运行时间为 %s 秒" %(end - start))
    return wrapper
@timmer
def i_can_sleep():
    time.sleep(3)
# 相当于 timmer(i_can_sleep())
i_can_sleep()

$ 运行时间为 3.0051488876342773
# 带参数的装饰器,复杂场景
def new_tips(argv):
    def tips(func):
        def nei(a,b):
            print('start %s %s' %(argv,func.__name__))
            func(a,b)
            print('stop')
        return nei
    return tips

@new_tips("add module")
def add(a,b):
    print(a+b)
@new_tips('sub module')
def sub(a, b):
    print(a-b)

print(add(4,5))
print(sub(7,3))

$ start add module add
$ 9
$ stop
$ None
$ start sub module sub
$ 4
$ stop
$ None

自定义上下文管理器

# 这两种写法相同
fd = open( 'name.txt')
try:
    for line in fd:
        print (line)
finally:
    fd.close()

with open('name.txt')as f:
    for line in f:
        print(line)

模块

模块是在代码量变大之后,为了将需要重复使用的有组织的代码段放在一起,这部分代码可以附加到现有的程序中,附加的过程叫做导入(import),

模块的定义

导入模块的一般写法:

import 模块名称
import 模块名称 as a
from 模块名称 import 方法名

类与实例

面向对象编程

# __name,属性前加__, 叫做类的封装,无法直接创建对象修改。
class Hero():
    '定义一个英雄类'
    # pass
    def __init__(self, name, hp=100, attack=10):
        self.__name = name
        self.__hp = hp
        self.__attack = attack

    def get_info(self):
        return "英雄 %s 的血量为 %s 攻击力为 %s " % (self.__name, self.__hp, self.__attack)

h1 = Hero("小明", 80, 5) # 类的实例化
print(h1.get_info())

增加类的属性和方法

    # 修改名称方法
    def update_name(self,new_name):
        self.__name = new_name
        
h1 = Hero("小明", 80, 10)
h1.update_name("小刚")
print(h1.get_info())

类的继承

Boss(Monster), 直接在()中写上父类名称,就可以继承。 super的使用

class Monster():
    '定义一个怪物类'
    def __init__(self, name, hp=100, attack=5):
        self.__name = name
        self.__hp = hp
        self.__attack = attack

    def get_info(self):
        print("Boss %s 的血量为 %s 攻击力为 %s " % (self.__name, self.__hp, self.__attack))

class Boss(Monster):
    '定义一个 Boss 类, 继承 Monster 类'
    def __init__(self, name, hp=400, attack=20):
        super.__init__(name, hp, attack)

使用 type 与 isinstance (判断是否是它的子类)判断类的关系

print(type(b1))
print(isinstance(b1, Hero))
print(isinstance(b1, Monster))
$ <class '__main__.Boss'>
$ False
$ True

类的使用-自定义 with 语句

# 正常 with 的使用
with open("diming.txt", encoding="utf-8") as f:
    pass
# 自定义 with 的使用
class TestWith():
    def __enter__(self):
        print('start')
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            print('end')
        else:
            print('error', exc_type, exc_val, exc_tb)
        print('exit')

with TestWith() as test:
    print("running test")
    raise NameError('testNameError') # 手动抛出异常

$ Traceback (most recent call last):
$   File "C:\Users\PyCharmMiscProject\test\with_test.py", line 13, in <module>
$     raise NameError('testNameError')
$ NameError: testNameError
$ start
$ running test
$ error <class 'NameError'> testNameError <traceback object at 0x0000021CB4B7BB80>
$ exit

多线程

多线程编程的定义

import threading
import time

def My_thread(arg1, arg2):
    print('thread', threading.current_thread().name, "start")
    time.sleep(1)
    print("running %s %s" % (arg1, arg2))
    print('thread', threading.current_thread().name, "stop")


for i in range(1, 5, 1):
    # t1 = My_thread(i, i + 1)
    t1 = threading.Thread(target=My_thread, args=(i, i + 1))
    t1.start()
    t1.join()

print('thread', threading.current_thread().name, "end")

$ thread Thread-1 (My_thread) start
$ running 1 2
$ thread Thread-1 (My_thread) stop
$ thread Thread-2 (My_thread) start
$ running 2 3
$ thread Thread-2 (My_thread) stop
$ thread Thread-3 (My_thread) start
$ running 3 4
$ thread Thread-3 (My_thread) stop
$ thread Thread-4 (My_thread) start
$ running 4 5
$ thread Thread-4 (My_thread) stop
$ thread MainThread end

经典的生产者与消费者问题

队列 queue

使用队列能够解决多线程中数据同步

import queue
# 创建一个队列
q = queue.Queue()
# 给队列增加数据
q.put(1)
q.put(2)
# 读取数据
print(q.get())
print(q.get())
import threading
import random
import time
from queue import Queue

queue = Queue(5)

class ProducerThread(threading.Thread):
    def run(self):
        name = threading.current_thread().name
        nums = range(100)
        global queue
        while True:
            num = random.choice(nums)
            queue.put(num)
            print("生产者 %s 生产了数据 %s" % (name, num))
            t = random.randint(1, 3)
            time.sleep(t)
            print("生产者 %s 睡眠了 %s 秒" % (name, t))

class ConsumerThread(threading.Thread):

    def run(self):
        name = threading.current_thread().name
        global queue
        while True:
            num = queue.get()
            queue.task_done()  # 封装好了线程等待与线程同步的方法
            print("消费者 %s 消费了数据 %s" % (name, num))
            t = random.randint(1, 3)
            time.sleep(t)
            print("消费者 %s 睡眠了 %s 秒" % (name, t))

p1 = ProducerThread(name="producer01")
p1.start()
c1 = ConsumerThread(name="consumer01")
c1.start()
c2 = ConsumerThread(name="consumer02")
c2.start()

$ 生产者 producer01 生产了数据 49
$ 消费者 consumer01 消费了数据 49
$ 消费者 consumer01 睡眠了 1 秒
$ 生产者 producer01 睡眠了 2 秒
$ 生产者 producer01 生产了数据 91
$ 消费者 consumer02 消费了数据 91
$ 消费者 consumer02 睡眠了 1 秒
$ 生产者 producer01 睡眠了 3

Python 标准库的定义

Python 标准库 — Python 3.13.3 文档 — The Python Standard Library — Python 3.13.3 documentation

常用的标准库:

Text Processing Services

Data Types 数据类型

Generic Operating System Services

Internet Data Handling

Development Tools 开发工具

正则表达式库 re

import re
# 匹配内容 a
q = re.compile("a")
# 要匹配的 a
print(q.match("a"))

$ <re.Match object; span=(0, 1), match='a'> # 匹配成功,位置0-1

正则表达式的元字符

. 匹配任意单个字符
^ 匹配已什么做开头 如 ^a
$ 匹配已什么做结尾 如 a$
* 匹配前面的字符出现0次或多次。 ca*t 与 caaat 或 ct 都可匹配
+ 匹配前面的字符出现1次或多次
? 匹配前面的字符出现0次或1次 
{m} 匹配前面的字符出现m次 ca{2}t 与 caat 可匹配
{m,n} 匹配前面的字符出现m到n次 ca{2,3}t 与 caat 、caaat 都可匹配
[] []之间的内容,只要匹配到就算匹配成功。 c[abc]t 与 cat cbt cct 能匹配成功 
| 或,一般与()一起使用
\d 匹配数字
\D 匹配非数字
\s 匹配字符串
() 分组
^$ 匹配空行
.*? 不使用贪婪模式
如 abcccccd, 使用 abc* 则可以匹配到 abccccc,使用abc*? 则只能匹配到 abc
使用 \r \n \d 等时,可以使用 r 不要转义,如 print(r"\n")
p = re.compile(r"(\d+)-(\d+)-(\d+)")
print(p.match("2025-5-29").group(1))
print(p.match("2025-5-29").groups())
year,month,day = p.match("2025-5-29").groups()
print(year,month,day)

$ 2025
$ ('2025', '5', '29')
$ 2025 5 29

match:必须完全匹配才可以

search: 搜索,支持不完全匹配

替换函数 sub

phone = "123-456-789 # 这是电话号码"
z = re.sub(r"#.*$","", phone)
print(z)
$ 123-456-789

文件夹操作库

import os

# 输出当前绝对路径
print(os.path.abspath("."))
# 判断文件是否存在
print(os.path.exists("/Users/nantian"))
# 目录连接
os.path.join("/Users/nantian","/a/a")

机器学习的一般流程

Numpy 库

用于高性能科学计算和数据分析,是常用的高级数据分析库的基础包. 如果没有需要安装 pip3 install numpy

Numpy 的数组与数据类型
import numpy as np

arr1 = np.array([1,2,3,4,5])
arr2 = np.array([1.1,2.2,3.3,4.4,5.5])
print(arr1)
print(arr1.dtype)
print(arr1 + arr2)

$ [1 2 3 4 5]
$ int64
$ [ 2.1  4.2  6.3  8.4 10.5]
Numpy 的数组和标量的计算
arr1 = np.array([1,2,3,4,5])
print(arr1 * 10)

$ [10 20 30 40 50]
-----------------------------------
data = [[1,2,3],[4,5,6]]
arr3 = np.array(data)
print(arr3)

$ [[1 2 3]
   [4 5 6]]
-----
# np的矩阵操作
print(np.zeros((3,5)))
print(np.ones((3,5)))
print(np.empty((2,3,2)))

$ [[0. 0. 0. 0. 0.]
$  [0. 0. 0. 0. 0.]
$  [0. 0. 0. 0. 0.]]
$ [[1. 1. 1. 1. 1.]
$  [1. 1. 1. 1. 1.]
$  [1. 1. 1. 1. 1.]]
$ [[[0. 0.]
$   [1. 1.]
$   [1. 1.]]
$ 
$  [[1. 1.]
$   [1. 0.]
$   [0. 1.]]]
Numpy 数组的索引和切片
arr4 = np.arange(10)
print(arr4)
arr4[2:4] = 10
print(arr4)
arr_slice = arr4[5:8].copy()
arr_slice[:] = 15
print(arr_slice)
print(arr4)

$ [0 1 2 3 4 5 6 7 8 9]
$ [ 0  1 10 10  4  5  6  7  8  9]
$ [15 15 15]
$ [ 0  1 10 10  4  5  6  7  8  9]

Pandas 库

将数据自动对齐显示。

可以灵活的处理缺失的数据。

可以将数据进行连接操作

Pandas 安装: pip3 install pandas

import pandas as pd
from pandas import DataFrame, Series

obj = Series([2,3,-4])
print(obj)
print(obj.index)
print(obj.values)

$ 0    2
$ 1    3
$ 2   -4
$ dtype: int64
$ RangeIndex(start=0, stop=3, step=1)
$ [ 2  3 -4]
Series 的基本操作

操作一维数据

obj2 = Series([4, 5, 7, -3], index=['a', 'd', 'b', 'c'])
print(obj2)
obj2['c']=7
print(obj2)
print('f' in obj2)

$ a    4
$ d    5
$ b    7
$ c   -3
$ dtype: int64
$ a    4
$ d    5
$ b    7
$ c    7
$ dtype: int64
$ False
# 定义一个字典, 转化 Series
sdata = {'beijing':800,'shanghai':900,'guangzhou':700,'shenzhen':850}
obj3 = Series(sdata)
print(obj3)
obj3.index=['bj','sh','gz','sz']
print(obj3)

$ beijing      800
$ shanghai     900
$ guangzhou    700
$ shenzhen     850
$ dtype: int64
$ bj    800
$ sh    900
$ gz    700
$ sz    850
$ dtype: int64
DataFrame 的基本操作

操作多维数据

from pandas import DataFrame

sdata = {'city': ['beijing', 'shanghai', 'guangzhou', 'shenzhen'],
         'year': [2016, 2019, 2025, 2024],
         'num': [800, 900, 700, 850]}
frame = DataFrame(sdata)
# 排序
frame2 = DataFrame(sdata, columns=['num', 'city', 'year'])

print(frame)
print(frame2)
# 提取一维表格
print(frame2['city'])
print(frame2.year)
# 增加新的列
frame2['new'] = 100
# 修改索引, fill_value 当某列数据为空,则填充为 0
obj4 = obj3.reindex(['a','b','c','d'], fill_value=0)

$         city  year  num
$ 0    beijing  2016  800
$ 1   shanghai  2019  900
$ 2  guangzhou  2025  700
$ 3   shenzhen  2024  850
$    num       city  year
$ 0  800    beijing  2016
$ 1  900   shanghai  2019
$ 2  700  guangzhou  2025
$ 3  850   shenzhen  2024
$ 0      beijing
$ 1     shanghai
$ 2    guangzhou
$ 3     shenzhen
$ Name: city, dtype: object
$ 0    2016
$ 1    2019
$ 2    2025
$ 3    2024
$ Name: year, dtype: int64
层次化索引
data3 = Series(np.random.randn(10),
               index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'],
                      [1, 2, 3, 1, 2, 3, 1, 2, 2, 4]])
print(data3)
print(data3['a'])
print(data3.unstack())

$ a  1    0.432685
$    2   -0.502024
$    3    1.032039
$ b  1   -1.545387
$    2   -1.830726
$    3    0.992068
$ c  1   -0.740893
$    2    0.145850
$ d  2   -0.784924
$    4   -0.380510
$ dtype: float64
$ 1    0.432685
$ 2   -0.502024
$ 3    1.032039
$ dtype: float64
$           1         2         3        4
$ a  0.432685 -0.502024  1.032039      NaN
$ b -1.545387 -1.830726  0.992068      NaN
$ c -0.740893  0.145850       NaN      NaN
$ d       NaN -0.784924       NaN -0.38051

Matplotlib 的安装与绘图

安装 pip3 install Matplotlib

网页数据采集

urllib 库

from urllib import request

url = "http://www.baidu.com"
print(request.urlopen(url).read().decode('utf8'))

常见的两种请求方式 get、post

from urllib import request
from urllib import parse

# GET
reponse = request.urlopen('http://httpbin.org/get', timeout=10)
print(reponse.read().decode('utf-8'))

# POST
data = bytes(parse.urlencode({'word': 'hello'}), 'utf-8')
reponse1 = request.urlopen('http://httpbin.org/post', data=data, timeout=10)
print(reponse1.read().decode('utf-8'))

http 头部信息的模拟

易混淆项

序列与元组与字典的属性,写法,用法与区别

1. 序列(Sequence)

定义:序列是有序的元素集合,支持通过索引访问元素。常见的序列类型包括列表(list)、元组(tuple)、字符串(str)等。

属性
  • 有序性:元素按顺序存储,可通过索引(如 seq[0])访问。
  • 可迭代:可用 for 循环遍历。
  • 支持切片:通过 seq[start:end:step] 提取子序列。
  • 通用操作
    • 加法(+)连接序列,乘法(*)重复序列。
    • 长度:len(seq)
    • 成员检查:element in seq
    • 方法:index()(查找元素位置)、count()(统计元素出现次数)。
写法
  • 列表(List):用方括号 [],可变。
    my_list = [1, 2, "hello", [3, 4]]
    
  • 字符串(String):用引号 ''"",不可变。
    my_str = "abc"
    
  • 元组(Tuple):用圆括号 (),不可变(详见下文)。
用法
  • 列表用于需要动态修改的集合(如增删元素)。
  • 字符串用于处理文本。
  • 序列的通用操作(如切片、遍历)适用于所有序列类型。

2. 元组(Tuple)

定义:元组是不可变序列,一旦创建,元素不可修改。

属性
  • 不可变性:无法增删改元素(但元素本身若是可变类型,如列表,其内容可以修改)。
  • 可哈希:可作为字典的键(前提是所有元素都是不可变类型)。
  • 性能:因不可变,通常比列表更高效。
写法
  • 圆括号 (),元素用逗号分隔。单元素元组需加逗号避免歧义:
    t1 = (1, 2, 3)
    t2 = (4,)      # 单元素元组
    t3 = 5, 6, 7   # 括号可省略
    
用法
  • 存储不可变数据(如配置项、坐标、数据库记录)。
  • 作为函数参数或返回值(保证数据不被修改)。
  • 字典的键(需不可变性)。

3. 字典(Dictionary)

定义:字典是键值对(Key-Value)的无序集合(Python 3.7+ 中保持插入顺序),属于映射类型。

属性
  • 键唯一性:键必须是不可变类型(如字符串、数字、元组),且唯一。
  • 可变性:可动态增删改键值对。
  • 高效查找:通过键快速查找值,时间复杂度为 O(1)。
写法
  • 花括号 {},键值对用 key: value 表示:
    my_dict = {"name": "Alice", "age": 25, 1: "id"}
    
  • 空字典:empty_dict = {}dict()
常用操作
  • 访问值:my_dict["name"]my_dict.get("name", default)(避免 KeyError)。
  • 添加/修改:my_dict["new_key"] = value
  • 删除:del my_dict["key"]my_dict.pop("key")
  • 方法:
    • keys():返回所有键。
    • values():返回所有值。
    • items():返回键值对(元组形式)。
    • update():合并字典。
用法
  • 存储关联数据(如用户信息、配置参数)。
  • 快速查找表(通过键高效检索)。

三者的区别

特性序列(如列表)元组字典
可变性可变(列表)或不可变(字符串)不可变可变
有序性有序有序无序(Python 3.7+ 有序)
元素类型单个元素单个元素键值对
访问方式索引(seq[0]索引(tuple[0]键(dict["key"]
哈希性列表不可哈希可哈希(若元素不可变)键必须可哈希
典型用途动态集合、迭代不可变数据、字典键快速查找、关联数据

示例对比

1. 创建与修改
# 列表(可变)
lst = [1, 2, 3]
lst[0] = 10       # 合法
lst.append(4)     # 合法

# 元组(不可变)
tup = (1, 2, 3)
tup[0] = 10       # 报错:TypeError

# 字典(可变)
dct = {"a": 1, "b": 2}
dct["c"] = 3      # 添加新键值对
dct["a"] = 100    # 修改值
2. 哈希性
# 元组作为字典的键
valid_key = (1, "apple")
dct = {valid_key: "value"}

# 列表不可作为键(报错:TypeError)
invalid_key = [1, 2]
dct = {invalid_key: "value"}  

总结

  • 序列适用于有序集合(列表动态修改,元组不可变,字符串处理文本)。
  • 字典适用于键值对映射和快速查找。
  • 选择依据:是否需要可变性、是否需键值对、是否需要哈希特性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值