Python中列表与元组的遍历与排序
文章目录
- Python中列表与元组的遍历与排序
- 遍历操作
- 1. 直接遍历元素
- 2. 通过索引遍历
- 3. 使用enumerate同时获取索引和值
- 4. 使用zip并行遍历多个序列
- 排序操作
- 列表排序
- 1. 原地排序 - sort()方法
- 2. 生成新列表 - sorted()函数
- 元组排序
- 复杂对象排序
- 性能比较
- 使用建议
Python中列表与元组的遍历与排序
遍历操作
列表和元组都支持多种遍历方式,因为它们都是可迭代对象。
1. 直接遍历元素
# 列表遍历
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:print(fruit)# 元组遍历
colors = ('red', 'green', 'blue')
for color in colors:print(color)
2. 通过索引遍历
# 列表索引遍历
for i in range(len(fruits)):print(f"Index {i}: {fruits[i]}")# 元组索引遍历
for i in range(len(colors)):print(f"Index {i}: {colors[i]}")
3. 使用enumerate同时获取索引和值
# 列表enumerate遍历
for index, fruit in enumerate(fruits):print(f"Index {index}: {fruit}")# 元组enumerate遍历
for index, color in enumerate(colors):print(f"Index {index}: {color}")
4. 使用zip并行遍历多个序列
names = ['Alice', 'Bob', 'Charlie']
ages = (24, 30, 28)for name, age in zip(names, ages):print(f"{name} is {age} years old")
排序操作
虽然列表是可变的、元组是不可变的,但它们的排序方式有所不同。
列表排序
列表有原地排序和生成新列表两种方式:
1. 原地排序 - sort()方法
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort() # 默认升序
print(numbers) # 输出: [1, 1, 2, 3, 4, 5, 9]# 降序排序
numbers.sort(reverse=True)
print(numbers) # 输出: [9, 5, 4, 3, 2, 1, 1]# 按自定义规则排序
words = ['banana', 'pie', 'Washington', 'book']
words.sort(key=len) # 指定排序关键字key,按单词长度排序。如果缺少,默认索引为0的子元素为关键字进行排序
print(words) # 输出: ['pie', 'book', 'banana', 'Washington']
2. 生成新列表 - sorted()函数
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers) # 不改变原列表
print(sorted_numbers) # 输出: [1, 1, 2, 3, 4, 5, 9]
print(numbers) # 原列表不变: [3, 1, 4, 1, 5, 9, 2]
元组排序
由于元组不可变,只能使用sorted()函数生成新的排序后的列表:
numbers_tuple = (3, 1, 4, 1, 5, 9, 2)
sorted_list = sorted(numbers_tuple) # 返回一个新列表
print(sorted_list) # 输出: [1, 1, 2, 3, 4, 5, 9]# 如果需要元组结果,可以转换回来
sorted_tuple = tuple(sorted(numbers_tuple))
print(sorted_tuple) # 输出: (1, 1, 2, 3, 4, 5, 9)
复杂对象排序
class Person:def __init__(self, name, age):self.name = nameself.age = agedef __repr__(self):return f"Person(name='{self.name}', age={self.age})"people = [Person('Alice', 25),Person('Bob', 20),Person('Charlie', 30)
]# 按年龄排序
people.sort(key=lambda p: p.age)
print(people)
# 输出: [Person(name='Bob', age=20), Person(name='Alice', age=25), Person(name='Charlie', age=30)]# 按姓名排序
sorted_people = sorted(people, key=lambda p: p.name)
print(sorted_people)
# 输出: [Person(name='Alice', age=25), Person(name='Bob', age=20), Person(name='Charlie', age=30)]
性能比较
- 遍历性能:列表和元组的遍历性能几乎相同
- 排序性能:
- 列表原地排序(
sort()
)最节省内存 sorted()
函数会创建新对象,内存消耗更大- 元组必须使用
sorted()
,因此会有额外开销
- 列表原地排序(
使用建议
- 需要修改原序列时使用列表和
sort()
- 需要保持数据不变时使用元组和
sorted()
- 对大型数据集排序时考虑使用
key
参数提高效率 - 复杂排序可以使用多个条件的元组作为key:
# 先按年龄升序,再按姓名降序 people.sort(key=lambda p: (p.age, -ord(p.name[0])))