Python列表推导式、附加、排序、长度[示例]
什么是 Python 列表?
列表顾名思义,就是一个容器,可以包含不同的 Python 对象,例如整数、单词、值等。它相当于其他编程语言中的数组。它用方括号表示(这是它与用圆括号分隔的元组的区别之一)。它也是可变的,也就是说,可以修改或更新;与不可变的元组不同。
Python 列表示例
Python 列表可以是同质的,即可以包含相同类型的对象;也可以是异质的,包含不同类型的对象。
同质列表的例子包括
list of integers = [1, 2, 3, 8, 33] list of animals = ['dog', 'cat', 'goat'] list of names = ['John', 'Travis', 'Sheila'] list of floating numbers = [2.2, 4.5, 9.8, 10.4]
异质列表的例子包括
[2, 'cat', 34.33, 'Travis'] [2.22, 33, 'pen']
访问列表中的值
要访问列表中的值,可以使用列表内对象的索引。Python 列表中的索引是指元素在有序列表中的位置。例如
list = [3, 22, 30, 5.3, 20]
- 上面列表中的第一个值 3,索引为 0
- 第二个值 22,索引为 1
- 第三个值 30,索引为 2
依此类推。要访问列表中的每个值,您可以使用
list[0] to access 3 list[1] to access 22 list[2] to access 30 list[3] to access 5.3 list[4] to access 20
还可以使用索引 -1 来访问列表的最后一个成员。例如,
list[-1] = 20
Python 列表切片
列表切片是通过分割列表的子集来完成的,列表对象的索引也用于此。例如,使用上面相同的列表示例;
list[:] = [3, 22, 30, 5.3, 20] (all the members of the list]; list[1:3] = [22, 30] (members of the list from index 1 to index 3, without the member at index 3); list[:4] = [3, 22, 30, 5.3] (members of the list from index 0 to index 4, without the member at index 4) list[2:-1] = [30, 5.3] (members of the list from index 2, which is the third element, to the second to the last element in the list, which is 5.3).
Python 列表是排他性的上界,这意味着列表切片中的最后一个索引通常会被忽略。这就是为什么
list[2:-1] = [30, 5.3]
而不是 [30, 5.3, 20]。上面所有其他的列表切片示例也一样。
更新列表
假设您有一个列表 list = [physics, chemistry, mathematics],并且您想将列表更改为 [biology, chemistry, mathematics],从而更改索引 0 处的成员。这可以通过将该索引赋值给您想要的新成员来轻松完成。
即,
list = [physics, chemistry, mathematics] list[0] = biology print(list)
输出:[biology, chemistry, mathematics]
这会将索引 0 处的成员(physics)替换为您想要的新值(chemistry)。这可以对您想要更改的列表中的任何成员或子集进行。
再举一个例子;假设您有一个名为 integers 的列表,其中包含数字 [2, 5, 9, 20, 27]。要用 10 替换该列表中的 5,您可以使用
integers = [2, 5, 9, 20, 27] integers[1] = 10 print(integers) >>> [2, 10, 9, 20, 27]
要用一个自由数(如 30.5)替换 integers 列表的最后一个成员(即 27),您可以使用
integers = [2, 5, 9, 20, 27] integers[-1] = 30.5 print(integers) >>> [2, 5, 9, 20, 30.5]
删除列表元素
有 3 种 Python 方法用于删除列表元素:list.remove()、list.pop() 和 del 运算符。Remove 方法将要删除的特定元素作为参数,而 pop 和 del 将要删除的元素的索引作为参数。例如
list = [3, 5, 7, 8, 9, 20]
要从列表中删除 3(第一个元素),您可以使用
- list.remove(3) 或
- list.pop[0] 或
- del list[0]
要从列表中删除 8(索引为 3 的项),您可以使用
- list.remove(8) 或
- list.pop[3]
追加列表元素
要将元素追加到列表中,可以使用 append 方法,它会将元素添加到列表的末尾。
例如
list_1 = [3, 5, 7, 8, 9, 20] list_1.append(3.33) print(list_1) >>> list_1 = [3, 5, 7, 8, 9, 20, 3.33] list_1.append("cats") print(list_1) >>> list_1 = [3, 5, 7, 8, 9, 20, 3.33, "cats"]
列表内置函数(方法)
以下是列表内置函数和方法的列表及其说明
- len(list):输出列表的长度。例如
numbers = [2, 5, 7, 9] print(len(numbers)) >>> 4
- max(list):返回列表中值最大的项。例如
numbers = [2, 5, 7, 9] print(max(numbers)) >>> 9
- min(list):返回列表中值最小的项。例如
numbers = [2, 5, 7, 9] print(min(numbers)) >>> 2
- list(tuple):将元组对象转换为列表。例如;
animals = (cat, dog, fish, cow) print(list(animals)) >>> [cat, dog, fish, cow]
- list.append(element):将元素追加到列表。例如;
numbers = [2, 5, 7, 9] numbers.append(15) print(numbers) >>> [2, 5, 7, 9, 15]
- list.pop(index):从列表中删除指定索引处的元素。例如;
numbers = [2, 5, 7, 9, 15] numbers.pop(2) print(numbers) >>> [2, 5, 9, 15]
- list.remove(element):从列表中删除元素。例如;
values = [2, 5, 7, 9] values.remove(2) print(values) >>> [5, 7, 9]
- list.reverse():反转列表中的对象。例如;
values = [2, 5, 7, 10] values.reverse() print(values) >>> [10, 7, 5, 2]
- list.index(element):获取列表中元素的索引值。例如;
animals = ['cat', 'dog', 'fish', 'cow', 'goat'] fish_index = animals.index('fish') print(fish_index) >>> 2
- sum(list):如果所有值都是数字(整数或小数),则获取列表中所有值的总和。例如;
values = [2, 5, 10] sum_of_values = sum(values) print(sum_of_values) >>> 17
如果列表中包含任何非数字元素(如字符串),则 sum 方法将不起作用。您会收到一条错误消息:“TypeError: unsupported operand type(s) for +: ‘int’ and ‘str'”
- list.sort():用于按升序或降序排列整数、浮点数或字符串列表。例如
values = [1, 7, 9, 3, 5] # To sort the values in ascending order: values.sort() print(values) >>> [1, 3, 5, 7, 9]
另一个例子
values = [2, 10, 7, 14, 50] # To sort the values in descending order: values.sort(reverse = True) print(values) >>> [50, 14, 10, 7, 2]
也可以按字母顺序或按字符串长度对字符串列表进行排序。例如;
# to sort the list by length of the elements strings = ['cat', 'mammal', 'goat', 'is'] sort_by_alphabet = strings.sort() sort_by_length = strings.sort(key = len) print(sort_by_alphabet) print(sort_by_length) >>> ['cat', 'goat', 'is', 'mammal'] ['is', 'cat', 'goat', 'mammal']
我们可以使用“字符串”按字母顺序对同一列表进行排序。
遍历列表
遍历列表的方式与其他 Python 循环函数相同。这样,就可以同时对列表中的多个元素执行一个方法。例如
list = [10, 20, 30, 40, 50, 60, 70]。
遍历此列表中的所有元素,并假设为每个元素加 10
for elem in list: elem = elem + 5 print(elem) >>>>15 25 35 45 55 65 75
遍历列表的前三个元素并删除它们;
for elem in list[:3]: list.remove(elem) >>>list = [40, 50, 60, 70]
遍历列表中的第 3 个(索引为 2)到最后一个元素,并将它们追加到一个名为 new_list 的新列表中
new_list = [] for elem in list[2:]: new_list.append(elem) print(“New List: {}”.format(new_list)) Output: New List: [30, 40, 50, 60, 70]
这样,可以应用任何方法或函数到列表的成员上以执行特定操作。您可以通过遍历列表的所有成员,或使用列表切片遍历列表的子集。
Python 列表推导式
列表推导式是 Python 函数,用于使用已创建的序列来创建新序列(如列表、字典等)。它们有助于减少较长的循环,并使您的代码更易于阅读和维护。
例如;假设您想创建一个包含 1 到 9 所有数字的平方的列表
list_of squares = [] for int in range(1, 10): square = int ** 2 list_of_squares.append(square) print(list_of_squares) List_of_squares using for loop: [1, 4, 9, 16, 25, 36, 49, 64, 81]
使用列表推导式做同样的事情
list_of_squares_2 = [int**2 for int in range(1, 10)] print('List of squares using list comprehension: {}'.format(list_of_squares_2)) Output using list comprehension: [1, 4, 9, 16, 25, 36, 49, 64, 81]
如上所示,使用列表推导式编写代码比使用传统的 for 循环要简短得多,而且速度也更快。这只是使用列表推导式代替 for 循环的一个例子,但这可以在许多可以使用 for 循环的地方进行复制和使用。有时,使用 for 循环是更好的选择,尤其是在代码复杂的情况下,但在许多情况下,列表推导式将使您的编码更轻松、更快。
下表包含一些列表函数和方法及其说明。
内置函数
函数 | 描述 |
---|---|
Round() | 将作为参数传递的数字四舍五入到指定的小数位数,并返回浮点值 |
Min() | 返回给定列表的最小元素 |
Max() | 返回给定列表的最大元素 |
len() | 返回列表的长度 |
Enumerate() | 此内置函数同时生成可迭代对象中各项的值和索引,因此我们无需手动计数 |
Filter() | 测试列表的每个元素是否为真 |
Lambda | 一个表达式,可以在创建函数时使用 def 不起作用的语法位置出现,例如在列表字面量或函数调用参数中 |
Map() | 将给定函数应用于给定可迭代对象的每个项后,返回结果列表 |
Accumulate() | 将参数中传递的特定函数应用于所有列表元素,并返回一个包含中间结果的列表 |
Sum() | 返回列表中所有数字的总和 |
Cmp() | 用于比较两个列表,如果第一个列表大于第二个列表,则返回 1。 |
插入 | 在特定位置插入列表元素 |
列表方法
函数 | 描述 |
---|---|
Append() | 在新项添加到列表末尾 |
Clear() | 删除列表中的所有项 |
Copy() | 返回原始列表的副本 |
Extend() | 将多个项添加到列表末尾 |
Count() | 返回列表中特定项的出现次数 |
Index() | 返回列表中特定元素的索引 |
Pop() | 从特定索引处的列表中删除项(按位置删除) |
Remove() | 从列表中删除指定项(按值删除) |
Reverse() | 原地反转方法,它会反转列表中元素的顺序 |
摘要
- 列表顾名思义,就是一个容器,可以包含不同的 Python 对象,例如整数、单词、值等。
- Python 列表可以是同质的,意味着它们可以包含相同类型的对象;也可以是异质的,包含不同类型的对象。
- 要访问列表中的值,可以使用列表内对象的索引。
- 列表切片是通过分割列表的子集来完成的,列表对象的索引也用于此。
- 删除列表元素的三个方法是:1)list.remove(),2)list.pop(),和 3)del 运算符
- Append 方法用于追加元素。这会将元素添加到列表的末尾。
- Python 程序的循环方法可以同时对数据列表的多个元素执行。
- 列表推导式是 Python 函数,用于使用已创建的序列来创建新序列(如列表、字典等)。