74 lines
1.8 KiB
Python
74 lines
1.8 KiB
Python
# 请详细说明它们的基本用法、区别、性能特点以及应用场景
|
|
|
|
# append、insert和extend都是Python列表操作方法,但它们有以下主要区别:
|
|
|
|
# append:在列表末尾添加单个元素
|
|
# insert:在列表指定位置插入单个元素
|
|
# extend:将另一个可迭代对象的所有元素添加到列表末尾
|
|
|
|
# **都没有返回值,直接修改元数据
|
|
|
|
my_list = [1, 2, 3]
|
|
|
|
my_list.append(4)
|
|
print(my_list)
|
|
|
|
|
|
# insert方法
|
|
# 功能描述: insert方法用于在列表的指定位置插入一个元素,需要两个参数:插入位置的索引和要插入的元
|
|
my_list = [1, 2, 3]
|
|
my_list.insert(2, "a")
|
|
print(my_list)
|
|
# 插到末尾
|
|
my_list.insert(len(my_list), ["end"])
|
|
print(my_list)
|
|
|
|
|
|
# 在有序列表中插入新元素并保持顺序
|
|
sorted_list = [1, 3, 5, 7, 9]
|
|
new_number = 10
|
|
|
|
# 寻找合适的位置
|
|
insert_index = 0
|
|
for index, item in enumerate(sorted_list):
|
|
if item > new_number:
|
|
insert_index = index
|
|
break
|
|
else:
|
|
insert_index = len(sorted_list)
|
|
|
|
sorted_list.insert(insert_index, new_number)
|
|
print(sorted_list)
|
|
|
|
|
|
# extend方法
|
|
# 功能描述: extend方法用于将另一个可迭代对象(如列表、元组、字符串等)的所有元素逐个添加到当前列表的末尾。
|
|
|
|
my_list = [1, 2, 3]
|
|
my_list.extend([4, 5])
|
|
|
|
my_list.extend((1, 2))
|
|
my_list.extend("str")
|
|
print(my_list) # [1, 2, 3, 4, 5, 1, 2, 's', 't', 'r']
|
|
|
|
# 应用
|
|
|
|
# 合并多个列表
|
|
list1 = [1, 2, 3]
|
|
list2 = [4, 5, 6]
|
|
list3 = [7, 8, 9]
|
|
|
|
new_list = []
|
|
new_list.extend(list1)
|
|
new_list.extend(list2)
|
|
new_list.extend(list3)
|
|
print(new_list)
|
|
|
|
# 处理嵌套数据结构
|
|
nested_lists = [[1, 2], [3, 4], [5, [6]]]
|
|
flattened = []
|
|
for arr in nested_lists:
|
|
flattened.extend(arr)
|
|
|
|
print(flattened) # 只能展开双层,如果三层就不行了 [1, 2, 3, 4, 5, [6]]
|