列表(list)篇(二)

文章目录

  • [2.10 insert()函数](#2.10 insert()函数)
  • [2.11 list()函数](#2.11 list()函数)
  • [2.12 pop() 函数](#2.12 pop() 函数)
  • [2.13 remove()函数](#2.13 remove()函数)
  • [2.14 reverse()函数](#2.14 reverse()函数)
  • [2.15 sort()函数](#2.15 sort()函数)
  • [2.16 sorted()函数](#2.16 sorted()函数)
  • [2.17 sum()函数](#2.17 sum()函数)

2.10 insert()函数

在Python中,list.insert()是一个列表方法,用于在指定索引位置插入一个元素。这个方法会改变原列表,插入新元素后,该位置及之后的元素都会向后移动一位。

list.insert()方法的语法如下:

python 复制代码
list.insert(index, object)
  • index:必需的参数,表示要插入元素的索引位置。
  • object:必需的参数,表示要插入的元素。

下面是一个使用insert()方法的例子:

python 复制代码
# 创建一个列表
my_list = ['apple', 'banana', 'cherry']

# 在索引1的位置插入元素'orange'
my_list.insert(1, 'orange')

# 打印修改后的列表
print(my_list)  # 输出: ['apple', 'orange', 'banana', 'cherry']

在这个例子中,insert()方法在索引1的位置插入了元素'orange'。原本在索引1位置的元素'banana'及其之后的元素都向后移动了一位。

请注意,如果指定的索引超出了列表的范围(即索引大于或等于列表的长度),insert()方法会在列表的末尾添加元素。如果索引是负数,它表示从列表的末尾开始计数的位置。例如,-1表示列表的最后一个元素,-2表示倒数第二个元素,依此类推。

下面是一个使用负索引的例子:

python 复制代码
# 创建一个列表
my_list = ['apple', 'banana', 'cherry']

# 在倒数第二个位置插入元素'orange'
my_list.insert(-2, 'orange')

# 打印修改后的列表
print(my_list)  # 输出: ['apple', 'orange', 'banana', 'cherry']

在这个例子中,insert()方法在倒数第二个位置(即原列表中索引1的位置)插入了元素'orange'。

2.11 list()函数

在Python中,list()是一个内置函数,用于将可迭代对象(如元组、字符串、集合或任何实现了迭代协议的对象)转换成一个列表。如果传递给list()的参数本身就是一个列表,那么它会返回该列表的一个浅拷贝。

以下是list()函数的一些用法示例:

python 复制代码
# 将一个元组转换为列表
tuple_example = (1, 2, 3)
list_from_tuple = list(tuple_example)
print(list_from_tuple)  # 输出: [1, 2, 3]

# 将一个字符串转换为字符列表
string_example = "hello"
list_from_string = list(string_example)
print(list_from_string)  # 输出: ['h', 'e', 'l', 'l', 'o']

# 将一个集合转换为列表
set_example = {4, 5, 6}
list_from_set = list(set_example)
print(list_from_set)  # 输出可能是: [4, 5, 6],但集合是无序的,所以顺序可能会有所不同

# 将一个字典的键转换为列表
dict_example = {'a': 1, 'b': 2, 'c': 3}
list_from_dict_keys = list(dict_example.keys())
print(list_from_dict_keys)  # 输出: ['a', 'b', 'c']

# 将一个字典的值转换为列表
list_from_dict_values = list(dict_example.values())
print(list_from_dict_values)  # 输出: [1, 2, 3]

# 将一个自定义可迭代对象转换为列表
class MyIterable:
    def __iter__(self):
        return iter([10, 20, 30])

my_iterable = MyIterable()
list_from_custom = list(my_iterable)
print(list_from_custom)  # 输出: [10, 20, 30]

# 创建一个空列表
empty_list = list()
print(empty_list)  # 输出: []

# 将一个列表复制(浅拷贝)
original_list = [1, 2, [3, 4]]
copied_list = list(original_list)
print(copied_list)  # 输出: [1, 2, [3, 4]]
# 注意,这里的copied_list和original_list中的嵌套列表是同一个对象

在最后一个例子中,即使我们使用了list()函数来复制了一个列表,嵌套列表仍然是原始列表中的同一个对象。这是因为list()函数执行的是浅拷贝(shallow copy),它只复制了最外层的列表,而列表中的元素(如果它们是可变对象)则保持不变。

如果你想要进行深拷贝(deep copy),使得嵌套列表也是新的对象,你需要使用copy模块的deepcopy函数:

python 复制代码
import copy

original_list = [1, 2, [3, 4]]
deep_copied_list = copy.deepcopy(original_list)
print(deep_copied_list)  # 输出: [1, 2, [3, 4]]
# 注意,这里的deep_copied_list和original_list中的嵌套列表不是同一个对象

list()函数在需要将其他可迭代对象转换为列表时非常有用,因为它提供了一种简单且通用的方法来创建列表。

2.12 pop() 函数

在Python中,list.pop()是一个列表方法,用于移除列表中的一个元素,并返回该元素的值。默认情况下,pop()方法移除并返回列表中的最后一个元素(索引为-1的元素)。如果提供了索引参数,那么它会移除并返回该索引位置的元素。

以下是list.pop()方法的基本语法:

python 复制代码
list.pop([index])
  • index(可选):要移除的元素的索引。如果不指定索引,默认为-1,即移除最后一个元素。

下面是一些使用pop()方法的例子:

python 复制代码
# 创建一个列表
my_list = [10, 20, 30, 40, 50]

# 移除并返回列表中的最后一个元素
last_element = my_list.pop()
print(f"Removed element: {last_element}, List now: {my_list}")
# 输出: Removed element: 50, List now: [10, 20, 30, 40]

# 移除并返回索引为1的元素
element_at_index_1 = my_list.pop(1)
print(f"Removed element: {element_at_index_1}, List now: {my_list}")
# 输出: Removed element: 20, List now: [10, 30, 40]

# 尝试移除不存在的索引位置的元素会抛出IndexError
try:
    my_list.pop(10)
except IndexError as e:
    print(f"An error occurred: {e}")
# 输出: An error occurred: pop index out of range

在第一个例子中,pop()方法没有指定索引,所以它移除了列表中的最后一个元素(50)。在第二个例子中,我们指定了索引1,所以移除了该位置的元素(20)。在最后一个例子中,尝试移除一个不存在的索引(10)会抛出一个IndexError异常,因为列表中没有索引为10的元素。

pop()方法是一个就地操作(in-place operation),它会直接修改原列表,而不是返回一个新的列表。如果你想要保留原列表并创建一个不包含被移除元素的新列表,你可以先复制原列表,然后再对新列表调用pop()方法。

2.13 remove()函数

在Python中,list.remove() 是一个列表方法,用于移除列表中第一个匹配到的指定值的元素。如果列表中有多个相同的元素,remove() 只会移除第一个出现的元素。如果列表中不存在该元素,remove() 会引发一个 ValueError 异常。

以下是 list.remove() 方法的基本语法:

python 复制代码
list.remove(value)
  • value:必需参数,表示要移除的元素的值。

下面是一个使用 remove() 方法的例子:

python 复制代码
# 创建一个列表
my_list = [1, 2, 3, 4, 3, 5]

# 移除第一个值为3的元素
my_list.remove(3)

# 打印修改后的列表
print(my_list)  # 输出: [1, 2, 4, 3, 5]

在这个例子中,remove() 方法移除了列表中第一个值为3的元素。

如果你尝试移除一个不存在的元素,会抛出 ValueError:

python 复制代码
# 创建一个列表
my_list = [1, 2, 3, 4, 5]

# 尝试移除一个不存在的元素
try:
    my_list.remove(6)
except ValueError as e:
    print(f"An error occurred: {e}")
# 输出: An error occurred: list.remove(x): x not in list

在这个例子中,因为6不在列表中,所以 remove() 方法抛出了一个 ValueError 异常。

如果你想移除列表中所有匹配的元素,而不是仅仅第一个,你需要使用循环来多次调用 remove() 方法,或者使用列表推导式来创建一个新的列表,其中不包含要移除的元素。例如:

python 复制代码
# 创建一个列表
my_list = [1, 2, 3, 4, 3, 5]

# 移除所有值为3的元素
while 3 in my_list:
    my_list.remove(3)

# 打印修改后的列表
print(my_list)  # 输出: [1, 2, 4, 5]

或者使用列表推导式:

python 复制代码
# 创建一个列表
my_list = [1, 2, 3, 4, 3, 5]

# 创建一个新列表,其中不包含值为3的元素
my_list = [x for x in my_list if x != 3]

# 打印修改后的列表
print(my_list)  # 输出: [1, 2, 4, 5]

这两种方法都会移除列表中所有值为3的元素。

2.14 reverse()函数

在Python中,list.reverse()是一个列表方法,用于原地(in-place)反转列表中的元素顺序。这意味着它不会创建一个新的列表,而是直接修改原列表。调用reverse()方法后,原列表的元素顺序会被反转,而方法本身没有返回值(返回None)。

以下是如何使用list.reverse()的示例:

python 复制代码
# 创建一个列表
my_list = [1, 2, 3, 4, 5]

# 打印原始列表
print("Original list:", my_list)
# 输出: Original list: [1, 2, 3, 4, 5]

# 反转列表
my_list.reverse()

# 打印反转后的列表
print("Reversed list:", my_list)
# 输出: Reversed list: [5, 4, 3, 2, 1]

# 注意:reverse()是原地操作,原列表被修改

在这个例子中,my_list.reverse()调用了reverse()方法,它直接修改了my_list,使其元素顺序颠倒。因此,在调用reverse()之后,my_list的内容发生了改变。

如果你想要得到一个反转后的新列表,而不改变原列表,你可以使用切片操作:

python 复制代码
# 创建一个列表
my_list = [1, 2, 3, 4, 5]

# 使用切片操作来反转列表,并创建一个新列表
reversed_list = my_list[::-1]

# 打印原始列表和新列表
print("Original list:", my_list)
# 输出: Original list: [1, 2, 3, 4, 5]

print("New reversed list:", reversed_list)
# 输出: New reversed list: [5, 4, 3, 2, 1]

# 注意:原列表未发生改变

在这个例子中,my_list[::-1]创建了一个新列表,它是原列表my_list的反转副本。原列表my_list的内容保持不变。

2.15 sort()函数

在Python中,list.sort()是一个列表方法,用于对列表中的元素进行排序。该方法会按照升序(从小到大)对原列表进行就地(in-place)排序,即不返回新列表,而是直接修改原列表。

list.sort()方法的基本语法如下:

python 复制代码
list.sort(key=None, reverse=False)
  • key:可选参数,用于指定一个函数,该函数将被用于在比较元素时提取比较键(comparison key)。默认值为None,表示直接比较元素本身。
  • reverse:可选参数,布尔值,默认为False。如果设置为True,则列表将按照降序(从大到小)排序。

下面是一些使用list.sort()方法的例子:

python 复制代码
# 创建一个列表
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# 对列表进行升序排序
my_list.sort()
print("Sorted list in ascending order:", my_list)
# 输出: Sorted list in ascending order: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

# 对列表进行降序排序
my_list.sort(reverse=True)
print("Sorted list in descending order:", my_list)
# 输出: Sorted list in descending order: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

# 使用key参数进行排序,例如按照字符串长度排序
words = ['apple', 'banana', 'cherry', 'date']
words.sort(key=len)
print("Words sorted by length:", words)
# 输出: Words sorted by length: ['date', 'apple', 'cherry', 'banana']

在第一个例子中,我们直接调用了sort()方法对列表进行升序排序,然后又用reverse=True参数进行了降序排序。在第二个例子中,我们使用了key参数来指定一个函数,该函数返回每个元素的长度,因此列表是按照字符串长度进行排序的。

需要注意的是,list.sort()是就地排序,这意味着它会直接修改原列表。如果你不想修改原列表,而是想保留原列表并创建一个新的已排序列表,你可以使用sorted()函数,该函数会返回一个新的已排序列表,原列表不会被修改。

python 复制代码
# 创建一个列表
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# 创建一个新的已排序列表,原列表不变
sorted_list = sorted(my_list)
print("Original list:", my_list)
# 输出: Original list: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

print("New sorted list:", sorted_list)
# 输出: New sorted list: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

在这个例子中,sorted()函数返回了一个新的已排序列表,而原列表my_list保持不变

2.16 sorted()函数

在Python中,sorted() 是一个内置函数,用于对可迭代对象(如列表)进行排序,并返回一个新的已排序的列表。原始列表不会被修改,因为sorted()函数返回一个新的列表。

sorted()函数的基本语法如下:

python 复制代码
sorted(iterable, key=None, reverse=False)
  • iterable:必需参数,表示要进行排序的可迭代对象,如列表。
  • key:可选参数,用于指定一个函数,该函数将被用于在比较元素时提取比较键(comparison key)。默认值为None,表示直接比较元素本身。
  • reverse:可选参数,布尔值,默认为False。如果设置为True,则返回的列表将按照降序排序。

以下是一些使用sorted()函数的例子:

python 复制代码
# 创建一个列表
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# 对列表进行升序排序
sorted_list = sorted(my_list)
print("Sorted list in ascending order:", sorted_list)
# 输出: Sorted list in ascending order: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

# 对列表进行降序排序
sorted_list_descending = sorted(my_list, reverse=True)
print("Sorted list in descending order:", sorted_list_descending)
# 输出: Sorted list in descending order: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

# 使用key参数进行排序,例如按照字符串长度排序
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key=len)
print("Words sorted by length:", sorted_words)
# 输出: Words sorted by length: ['date', 'apple', 'cherry', 'banana']

在第一个例子中,我们使用了sorted()函数对列表进行升序排序,并打印了排序后的新列表。在第二个例子中,我们通过设置reverse=True参数来对列表进行降序排序。在第三个例子中,我们使用key参数来指定一个函数,该函数返回每个元素的长度,因此列表是按照字符串长度进行排序的。

需要注意的是,sorted()函数返回的是一个新的列表,而原始列表my_list保持不变。如果你想要在原地修改列表并排序,可以使用列表的sort()方法,如之前所提到的。

2.17 sum()函数

在Python中,sum()是一个内置函数,用于计算可迭代对象(如列表)中所有元素的和。当你对列表使用sum()函数时,它会返回列表中所有元素相加的结果。

以下是如何使用sum()函数来计算列表元素之和的示例:

python 复制代码
# 创建一个数值列表
my_list = [1, 2, 3, 4, 5]

# 使用sum()函数计算列表中所有元素的和
total = sum(my_list)

# 打印结果
print("Sum of the list elements:", total)
# 输出: Sum of the list elements: 15

在这个例子中,sum(my_list)计算了列表my_list中所有数字的和,并将结果存储在变量total中。然后,我们打印了这个和。

sum()函数也可以与字符串列表一起使用,但在这种情况下,它将连接字符串而不是计算它们的和:

python 复制代码
# 创建一个字符串列表
string_list = ["Hello", " ", "World"]

# 使用sum()函数连接字符串列表中的元素
combined_string = sum(string_list)

# 打印结果
print("Combined string:", combined_string)
# 输出: Combined string: Hello World

在这个例子中,sum(string_list)将列表string_list中的所有字符串连接起来,形成一个单一的字符串。

如果你想要对列表中的元素应用某种数学运算(如乘法)并求和,你可以使用列表推导式与sum()函数结合:

python 复制代码
# 创建一个数值列表
my_list = [1, 2, 3, 4, 5]

# 使用列表推导式和sum()函数计算列表中每个元素的平方和
total_squared = sum(x**2 for x in my_list)

# 打印结果
print("Sum of squares:", total_squared)
# 输出: Sum of squares: 55

在这个例子中,列表推导式x**2 for x in my_list生成了一个新的列表,其中包含my_list中每个元素的平方。然后,sum()函数计算了这个新列表中所有元素的和。

相关推荐
数据智能老司机1 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机2 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机2 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机2 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i2 小时前
drf初步梳理
python·django
每日AI新事件2 小时前
python的异步函数
python
这里有鱼汤4 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook13 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室13 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三15 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试