Files
notes_estom/Python/python3/2.3列表.md
2020-09-23 13:41:55 +08:00

7.6 KiB
Raw Blame History

Python 列表

原文: https://thepythonguru.com/python-lists/


于 2020 年 1 月 7 日更新


列表类型是 python 的列表类定义的另一种序列类型。 列表允许您以非常简单的方式添加,删除或处理元素。 列表与数组非常相似。

在 python 中创建列表


您可以使用以下语法创建列表。

>>> l = [1, 2, 3, 4]

在此,列表中的每个元素都用逗号分隔,并用一对方括号([])包围。 列表中的元素可以是相同类型或不同类型。 例如:

l2 = ["this is a string", 12]

创建列表的其他方式。

list1 = list() # Create an empty list
list2 = list([22, 31, 61]) # Create a list with elements 22, 31, 61
list3 = list(["tom", "jerry", "spyke"]) # Create a list with strings
list5 = list("python") # Create a list with characters p, y, t, h, o, n

注意

列表是可变的。

访问列表中的元素


您可以使用索引运算符([])访问列表中的各个元素。 列表索引从0开始。

>>> l = [1,2,3,4,5]
>>> l[1] # access second element in the list
2
>>> l[0] # access first element in the list
1

常用列表操作


方法名称 描述
x in s 如果元素x在序列s中,则为True,否则为False
x not in s 如果元素x不在序列s中,则为True,否则为False
s1 + s2 连接两个序列s1s2
s * nn * s 连接序列sn个副本
s[i] 序列s的第i个元素。
len(s) 序列s的长度,也就是元素数量。
min(s) 序列s中最小的元素。
max(s) 序列s中最大的元素。
sum(s) 序列s中所有数字的总和。
for循环 for循环中从左到右遍历元素。

列表函数示例


>>> list1 = [2, 3, 4, 1, 32]
>>> 2 in list1
True
>>> 33 not in list1
True
>>> len(list1) # find the number of elements in the list
5
>>> max(list1) # find the largest element in the list
32
>>> min(list1) # find the smallest element in the list
1
>>> sum(list1) # sum of elements in the list
42

列表切片


切片运算符([start:end])允许从列表中获取子列表。 它的工作原理类似于字符串。

>>> list = [11,33,44,66,788,1]
>>> list[0:5] # this will return list starting from index 0 to index 4
[11,33,44,66,788]

>>> list[:3] 
[11,33,44]

类似于字符串start的索引是可选的,如果省略,它将为0

>>> list[2:] 
[44,66,788,1]

end索引也是可选的,如果省略,它将被设置为列表的最后一个索引。

注意

如果为start >= end,则list[start : end]将返回一个空列表。 如果end指定的位置超出列表的end,则 Python 将使用end的列表长度。

列表中的+*运算符


+运算符加入两个列表。

>>> list1 = [11, 33]
>>> list2 = [1, 9]
>>> list3 = list1 + list2
>>> list3
[11, 33, 1, 9]

*操作符复制列表中的元素。

>>> list4 = [1, 2, 3, 4]
>>> list5 = list4 * 3
>>> list5
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

innot in运算符


in运算符用于确定列表中是否存在元素。 成功则返回True;失败则返回False

>>> list1 = [11, 22, 44, 16, 77, 98]
>>> 22 in list1
True

同样,not inin运算符相反。

>>> 22 not in list1
False

使用for循环遍历列表


如前所述,列表是一个序列并且也是可迭代的。 意味着您可以使用for循环遍历列表的所有元素。

>>> list = [1,2,3,4,5]
>>> for i in list:
... print(i, end=" ")
1 2 3 4 5

常用列表方法和返回类型


方法 描述
append(x: object): None 在列表的末尾添加元素x并返回None
count(x: object): int 返回元素x在列表中出现的次数。
append(l: list): None l中的所有元素附加到列表中并返回None
index(x: object): int 返回列表中第一次出现的元素x的索引
insert(index: int, x: object): None 在给定索引处插入元素x。 请注意,列表中的第一个元素具有索引0并返回None
remove(x: object): None 从列表中删除第一次出现的元素x并返回None
reverse(): None 反转列表并返回None
sort(): None 按升序对列表中的元素进行排序并返回None
pop(i): object 删除给定位置的元素并返回它。 参数i是可选的。 如果未指定,则pop()删除并返回列表中的最后一个元素。
copy():object 返回一个复制
clear() 移除所有元素del a[:]
list.extend(iterable) 使用可迭代对象中的所有元素来扩展列表。
>>> list1 = [2, 3, 4, 1, 32, 4]
>>> list1.append(19)
>>> list1
[2, 3, 4, 1, 32, 4, 19]
>>> list1.count(4) # Return the count for number 4
2
>>> list2 = [99, 54]
>>> list1.extend(list2)
>>> list1
[2, 3, 4, 1, 32, 4, 19, 99, 54]
>>> list1.index(4) # Return the index of number 4
2
>>> list1.insert(1, 25) # Insert 25 at position index 1
>>> list1
[2, 25, 3, 4, 1, 32, 4, 19, 99, 54]
>>>
>>> list1 = [2, 25, 3, 4, 1, 32, 4, 19, 99, 54]
>>> list1.pop(2)
3
>>> list1
[2, 25, 4, 1, 32, 4, 19, 99, 54]
>>> list1.pop()
54
>>> list1
[2, 25, 4, 1, 32, 4, 19, 99]
>>> list1.remove(32) # Remove number 32
>>> list1
[2, 25, 4, 1, 4, 19, 99]
>>> list1.reverse() # Reverse the list
>>> list1
[99, 19, 4, 1, 4, 25, 2]
>>> list1.sort() # Sort the list
>>> list1
[1, 2, 4, 4, 19, 25, 99]
>>>

列表推导式


注意

本主题需要具有 Python 循环的使用知识。

列表理解为创建列表提供了一种简洁的方法。 它由包含表达式的方括号组成,后跟for子句,然后是零个或多个forif子句。

这里有些例子:

>>> list1 = [ x for x in range(10) ]
>>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>>
>>> list2 = [ x + 1 for x in range(10) ]
>>> list2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
>>>
>>> list3 = [ x for x in range(10) if x % 2 == 0 ]
>>> list3
[0, 2, 4, 6, 8]
>>>
>>>
>>> list4 = [ x *2 for x in range(10) if x % 2 == 0 ]
[0, 4, 8, 12, 16]

列表作为栈使用

列表方法使得列表作为堆栈非常容易,最后一个插入,最先取出(“后进先出”)。要添加一个元素到堆栈的顶端,使用 append() 。要从堆栈顶部取出一个元素,使用 pop() ,不用指定索引。例如

>>>
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

列表作为队列使用

列表也可以用作队列,其中先添加的元素被最先取出 (“先进先出”);然而列表用作这个目的相当低效。因为在列表的末尾添加和弹出元素非常快,但是在列表的开头插入或弹出元素却很慢 (因为所有的其他元素都必须移动一位)。

若要实现一个队列,可使用 collections.deque它被设计成可以快速地从两端添加或弹出元素。例如

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])