Python 列表和字典方法详解

本文将详细介绍 Python 列表和字典的内置方法及其使用。通过这些方法,你可以对列表和字典进行高效的操作和管理,从而使你的 Python 编程更加灵活和高效。

Python 列表方法详解

Python 的列表(list)是一种可变的序列类型,用于存储元素集合。列表是 Python 中最常用的数据结构之一,其提供了一系列内置方法,使得列表的操作变得非常灵活和方便。

1. append(x)

append(x) 方法用于在列表末尾添加一个元素。这是最常用的列表方法之一,适用于动态地构建列表。

python 复制代码
fruits = ['apple', 'banana']
fruits.append('cherry')
print(fruits)  # 输出: ['apple', 'banana', 'cherry']

2. extend(iterable)

extend(iterable) 方法将一个可迭代对象(如列表、元组、集合)的所有元素添加到列表的末尾。

python 复制代码
fruits = ['apple', 'banana']
more_fruits = ['cherry', 'date']
fruits.extend(more_fruits)
print(fruits)  # 输出: ['apple', 'banana', 'cherry', 'date']

3. insert(i, x)

insert(i, x) 方法在指定位置插入一个元素。第一个参数是新元素将要插入的位置索引。

python 复制代码
fruits = ['apple', 'banana']
fruits.insert(1, 'cherry')
print(fruits)  # 输出: ['apple', 'cherry', 'banana']

4. remove(x)

remove(x) 方法移除列表中第一个值为 x 的元素。如果没有这样的元素,Python 会抛出一个错误。

python 复制代码
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits)  # 输出: ['apple', 'cherry']

5. pop(i)

pop([i]) 方法移除列表中指定位置的元素,并返回该元素的值。如果没有指定位置,pop() 将移除并返回列表中的最后一个元素。

python 复制代码
fruits = ['apple', 'banana', 'cherry']
fruit = fruits.pop(1)
print(fruit)  # 输出: 'banana'
print(fruits)  # 输出: ['apple', 'cherry']

6. clear()

clear() 方法移除列表中的所有项,等同于删除所有元素。

python 复制代码
fruits = ['apple', 'banana', 'cherry']
fruits.clear()
print(fruits)  # 输出: []

7. index(x, start\[, end])

index(x) 方法返回列表中第一个值为 x 的元素的索引。可以指定一个范围进行搜索。

python 复制代码
fruits = ['apple', 'banana', 'cherry']
index = fruits.index('cherry')
print(index)  # 输出: 2

8. count(x)

count(x) 方法返回 x 在列表中出现的次数。

python 复制代码
fruits = ['apple', 'banana', 'cherry', 'banana']
count = fruits.count('banana')
print(count)  # 输出: 2

9. sort(key=None, reverse=False)

sort() 方法对列表进行排序。

python 复制代码
fruits = ['banana', 'apple', 'cherry']
fruits.sort()
print(fruits)  # 输出: ['apple', 'banana', 'cherry']

# 降序排序
fruits.sort(reverse=True)
print(fruits)  # 输出: ['cherry', 'banana', 'apple']

10. reverse()

reverse() 方法倒排列表中的元素。

python 复制代码
fruits = ['banana', 'apple', 'cherry']
fruits.reverse()
print(fruits)  # 输出: ['cherry', 'apple', 'banana']

11. copy()

copy() 方法返回列表的一个浅复制。

python 复制代码
fruits = ['apple', 'banana', 'cherry']
fruits_copy = fruits.copy()
print(fruits_copy)  # 输出: ['apple', 'banana', 'cherry']

Python 字典方法详解

Python 的字典(dict)是一种内置的数据类型,用于存储键值对的集合。字典是无序的,但它们的键必须是唯一的。

1. clear()

clear() 方法用于移除字典内的所有项。

python 复制代码
dict = {'name': 'John', 'age': 25}
dict.clear()
print(dict)  # 输出: {}

2. copy()

copy() 方法返回字典的一个浅复制。

python 复制代码
original = {'name': 'John', 'age': 25}
copy = original.copy()
print(copy)  # 输出: {'name': 'John', 'age': 25}

3. fromkeys(seq, value)

fromkeys() 方法创建一个新字典,使用序列 seq 中的元素作为键,所有键默认对应的值为 None,除非指定了 value

python 复制代码
keys = ['name', 'age']
dict = dict.fromkeys(keys)
print(dict)  # 输出: {'name': None, 'age': None}

dict = dict.fromkeys(keys, 10)
print(dict)  # 输出: {'name': 10, 'age': 10}

4. get(key, default)

get() 方法返回字典中 key 对应的值。如果键不存在,返回 default 指定的值,默认为 None

python 复制代码
person = {'name': 'John', 'age': 25}
print(person.get('name'))  # 输出: John
print(person.get('address'))  # 输出: None
print(person.get('address', 'Not Found'))  # 输出: Not Found

5. items()

items() 方法以列表返回可遍历的 (键, 值) 元组数组。

python 复制代码
person = {'name': 'John', 'age': 25}
print(list(person.items()))  # 输出: [('name', 'John'), ('age', 25)]

6. keys()

keys() 方法以列表返回一个字典所有的键。

python 复制代码
person = {'name': 'John', 'age': 25}
print(list(person.keys()))  # 输出: ['name', 'age']

7. pop(key, default)

pop() 方法删除字典给定键 key 所对应的值,返回这个值。key 值必须给出。否则,返回 default 值。

python 复制代码
person = {'name': 'John', 'age': 25}
print(person.pop('age'))  # 输出: 25
print(person)  # 输出: {'name': 'John'}

8. popitem()

popitem() 方法随机返回并删除字典中的最后一对键和值。

python 复制代码
person = {'name': 'John', 'age': 25}
print(person.popitem())  # 输出: ('age', 25)
print(person)  # 输出: {'name': 'John'}

9. setdefault(key, default)

setdefault() 方法返回指定键的值。如果键不在字典中,插入键并将值设为 default,默认为 None

python 复制代码
person = {'name': 'John'}
print(person.setdefault('age', 25))  # 输出: 25
print(person)  # 输出: {'name': 'John', 'age': 25}

10. update(other)

update() 方法用于更新字典。它可以接受另一个字典或可迭代对象的键/值对来更新现有的条目。

python 复制代码
person = {'name': 'John', 'age': 25}
person.update({'age': 26, 'city': 'New York'})
print(person)  # 输出: {'name': 'John', 'age': 26, 'city': 'New York'}

11. values()

values() 方法以列表形式返回字典中的所有值。

python 复制代码
person = {'name': 'John', 'age': 25}
print(list(person.values()))  # 输出: ['John', 25]
相关推荐
北斗落凡尘7 小时前
LangGraph 入门实战(2)
python·langchain
ttod_qzstudio8 小时前
Java 常用语法极简通关(五):类与对象——字段、方法、构造器、this 与 static
java·开发语言·python
jufeng13079 小时前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 1 篇】
人工智能·python·架构·agent
月光船幽幽10 小时前
影子模式下保护 logits 不被修改
人工智能·python·算法
_oP_i12 小时前
python 后缀 mjs文件
开发语言·python
北斗落凡尘12 小时前
如何使用LangGraph(1)
python·langchain
Livia要学习13 小时前
Python装饰器
开发语言·python
大模型丫丫14 小时前
LangChain4j:Java 生态的 AI 应用开发利器
java·人工智能·python
circuitsosk14 小时前
向量数据库选型与性能压测:Milvus、Pinecone、Chroma在真实业务下的对比
数据库·python·pinecone·milvus·向量数据库·chroma
雾时之林14 小时前
python--字符串
开发语言·python