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]
相关推荐
你好潘先生4 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师4 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码4 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf4 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes17 小时前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户83562907805119 小时前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent1 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6251 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
SelectDB2 天前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码2 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python