Python列表和字典完全指南:从基础到实战应用
本文最后更新于68 天前,其中的信息可能已经过时,如有错误请发送邮件到big_fw@foxmail.com

Python中列表和字典的使用方法详解

列表(List)的基本操作

列表是Python中最常用的数据结构之一,它是一个有序的可变集合,可以包含不同类型的元素。

创建列表

# 空列表
empty_list = []

# 包含元素的列表
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'cherry']
mixed = [1, 'hello', 3.14, True]

访问列表元素

fruits = ['apple', 'banana', 'cherry']

# 通过索引访问
print(fruits[0])  # 输出: apple
print(fruits[-1]) # 输出: cherry (负索引从末尾开始)

# 切片操作
print(fruits[1:3]) # 输出: ['banana', 'cherry']

修改列表

fruits = ['apple', 'banana', 'cherry']

# 修改元素
fruits[1] = 'blueberry'
print(fruits)  # ['apple', 'blueberry', 'cherry']

# 添加元素
fruits.append('orange')      # 末尾添加
fruits.insert(1, 'mango')    # 指定位置插入

# 删除元素
del fruits[0]                # 删除指定位置元素
fruits.remove('blueberry')   # 删除指定值元素
popped = fruits.pop()        # 删除并返回最后一个元素

常用列表方法

numbers = [1, 2, 3, 4, 5]

# 长度
print(len(numbers))      # 5

# 排序
numbers.sort()           # 升序排序
numbers.sort(reverse=True) # 降序排序

# 反转
numbers.reverse()

# 查找索引
index = numbers.index(3)

# 统计出现次数
count = numbers.count(2)

# 清空列表
numbers.clear()

字典(Dictionary)的基本操作

字典是Python中另一种重要的数据结构,它以键值对的形式存储数据,具有极快的查找速度。

创建字典

# 空字典
empty_dict = {}

# 包含键值对的字典
person = {
    'name': 'Alice',
    'age': 25,
    'city': 'New York'
}

# dict()构造函数创建
another_dict = dict(name='Bob', age=30)

访问字典元素

person = {'name': 'Alice', 'age': 25}

# 通过键访问值
print(person['name'])   # Alice

# get()方法更安全,键不存在时返回None或默认值
print(person.get('age'))      # 25
print(person.get('height'))   # None
print(person.get('height', 'unknown')) # unknown

修改字典

person = {'name': 'Alice', 'age': 25}

# 添加/修改键值对
person['city'] = 'New York'
person['age'] = 26

# update()方法批量更新
person.update({'age': 27, 'job': 'Engineer'})

# del删除键值对
del person['city']

# pop()删除并返回值
age = person.pop('age')

常用字典方法

person = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# keys()获取所有键
print(person.keys())     # dict_keys(['name', 'age', 'city'])

# values()获取所有值  
print(person.values())   # dict_values(['Alice', 25, 'New York'])

# items()获取所有键值对
print(person.items())    # dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])

# in检查键是否存在
print('name' in person)   # True

# len()获取键值对数量  
print(len(person))       # 3

# clear()清空字典  
person.clear()

实际应用示例

列表和字典结合使用

# 学生信息管理系统示例
students = [
    {'name': 'Alice', 'age': 20, 'grades': [85, 90, 78]},
    {'name': 'Bob', 'age': 21, 'grades': [92, 88, 95]},
    {'name': 'Charlie', 'age': 19, 'grades': [78, 85, 80]}
]

# 计算每个学生的平均分
for student in students:
    grades = student['grades']
    average = sum(grades) / len(grades)
    student['average'] = round(average, 2)

# 按平均分排序学生  
students_sorted = sorted(students, key=lambda x: x['average'], reverse=True)

for student in students_sorted:
    print(f"{student['name']}: {student['average']}")

Python中的列表推导式和字典推导式

# 列表推导式示例:生成平方数列表  
squares = [x**2 for x in range(10)]
print(squares)   # [0,1,4,9,16,25,36,49,64,81]

# 字典推导式示例:创建数字到其平方的映射  
square_dict = {x: x**2 for x in range(5)}
print(square_dict)   # {0:0,1:1,2:4,3:9,4:16}

#带条件的推导式  
even_squares = [x**2 for x in range(10) if x %2 ==0]
print(even_squares)   #[0,4,16,36,64]

掌握Python中列表和字典的使用方法是编写高效Python代码的基础。这两种数据结构灵活且功能强大,几乎在所有的Python项目中都会用到。

文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇