简单 Python 快乐之旅之:Python 基础语法之列表操作专题

文章目录


在同系列博客《 简单 Python 快乐之旅之:Python 基础语法之循环关键字的使用例子》中我们对列表的定义及使用做了一个初步认识。本文将会对其操作进行深入一些的认识。
Python 列表允许存放异构类型的元素。这和其他主流语言中的列表或者数组是不一样的。但 Python 列表将足以满足你可能需要数组的所有需求。在本文中,我们将会学习到以下内容:如何在 Python 中创建一张列表;访问列表中的元素;查找列表中元素的个数;如何添加一个新元素到列表;如何在列表中删除某项;列表元素遍历;列表排序;列表反转;以及更多 Python 列表的转化和聚合操作。

1. 创建一个空列表

Python 列表是一种可以存储多种不同类型元素的数据结构。
通过给变量分配空的中括号即可创建一个空列表。

mylist = []

1.1. 示例:创建一个空列表

接下来的示例中,我们创建了一个空列表并检查其数据类型。

cars = []
print(type(cars))
print(len(cars))

执行和输出:
创建一个空列表.png
其长度输出为零。

2. 访问列表元素

可以像数组那样使用索引来单独访问一个列表项。你也可以使用范围索引来访问多个列表项。

mylist[5]
mylist[2:7]

如果你要对列表进行遍历请参考:循环列表项。

2.1. 示例:访问 Python 列表中的单个项

你可以在列表参数名后边加上中括号和索引来访问单个项。
在接下来的示例中,我们创建了一个 Python 列表,然后访问第三个项。由于索引起始于 0,索引的第三个项为 2。

# Access a single item of Python List
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
# access 3rd item with index 2
x = a[2]
print(x)
print(type(x))

执行和输出:
访问 Python 列表中的单个项.png

2.2. 访问 Python 列表中的多个项

通过提供范围索引,你还可以该列表的子列表或多个项。
在接下来的示例中,我们创建了一个索引,然后访问从第 2 到第 5 项,除最后一个索引所指示项的总计三个项。

# Access a range of items in Python List
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
# access a range of items
x = a[1:4]
print(x)
print(type(x))

执行和输出:
访问 Python 列表中的多个项.png

3. 列表长度

其实本文第 1. 节中已经用到了,将列表作为参数调用 Python 的全局函数就可以得到列表长度。
查找列表长度的 len() 函数语法如下:

len(listname)

该函数返回存在于列表中的项的个数。
在接下来的例子中,我们创建了一个列表,然后是要 len() 函数查出了其中所包含项的个数。

# Python List Length
cars = ['Ford', 'Volvo', 'BMW', 'Tesla']
length = len(cars)
print('Length of the list is:', length)

执行和输出:
列表长度.png

4. 添加元素

向 Python 列表添加元素使用列表对象的 append() 函数。使用 append() 函数的语法如下:

mylist.append(new_element)

new_element 是要追加到列表 mylist 中的新元素。

4.1. 示例:添加新元素到列表

在接下来的示例中,我们新建了一个列表,然后向它追加了一个新元素。

# Python List – Append or Add Item
cars = ['Ford', 'Volvo', 'BMW', 'Tesla']
cars.append('Audi')
print(cars)

执行和输出:
添加元素.png

5. 移除元素

移除 Python 列表中的某项可以使用列表对象的 remove() 函数,使用该方法语法如下:

mylist.remove(thisitem)

thisitem 是要从 mylist 中移除的那一项。
remove() 函数只会移除掉该项在列表中第一次出现的那一个,其余后续的会保留。后续我们还会学到怎么将特定值的项全部移除。

5.1. 移除在列表中只出现一次的元素

接下来的示例中我们新建了一个包含多个元素的列表,然后将只出现一次的元素 5 移除。

# Remove item that is present only once in the List
mylist = [21, 5, 8, 52, 21, 87]
item = 5
# remove the item
mylist.remove(item)
print(mylist)

执行和输出:
移除在列表中只出现一次的元素.png
可以看出该项已移除,它后边的每项的索引减一。

5.2. 移除出现多次的元素

在接下来的示例中,我们新建了一个包含多个元素的列表,而要移除的项 21,在列表中出现了两次。

# Remove item that is present multiple times in the List
mylist = [21, 5, 8, 52, 21, 87]
item = 21
# remove the item
mylist.remove(item)
print(mylist)

执行和输出:
移除出现多次的元素.png
可以看出虽然该项出现了两次,但是只是第一次出现的那个被移除了。

5.3. 移除出现多次的元素的所有项

在本示例中,我们自定义算法将出现过多次的给定项 21 都删除掉。

# Remove all the occurrences of an item from the List
mylist = [21, 5, 8, 52, 21, 87]
item = 21
# remove the item for all its occurrences
for r_item in mylist:
    if (item == r_item):
        mylist.remove(item)
print(mylist)

执行和输出:
移除出现多次的元素的所有项.png

6. 移除在列表中出现过多次的某个项

有三种办法可以移除掉在列表中出现过多次的给定项。

  • 遍历列表并移除可以匹配到指定值的项。
  • 使用 lambda 函数将不匹配到指定值的项过滤出来。
  • 重复使用 remove() 方法直到指定值不存在于列表中。
    推荐使用第二种方法,因为它能提供较好的性能。另外两种只是便于理解。

6.1. 使用 for 循环和 remove() 方法移除

遍历列表,一旦发现匹配指定值的项,调用 remove() 方法将其移除。上一节中已做介绍,这里不再赘述。

6.2. 过滤掉所有匹配项

将所有不匹配指定值的项都过滤出来。

# Remove all occurrences in List using Filter
mylist = [21, 5, 8, 52, 21, 87]
r_item = 21
# remove the item for all its occurrence
mylist = list(filter((r_item).__ne__, mylist))
print(mylist)
# Remove all occurrences in List using Filter
mylist = [21, 5, 8, 52, 21, 87]
r_item = 21
# keep the item for all its occurrence
mylist = list(filter((r_item).__eq__, mylist))
print(mylist)

执行和输出:
过滤掉所有匹配项.png

6.3. 使用 while 循环和 remove() 方法移除

只要列表含有有匹配项,即移除第一项,直到没有匹配项。

# Remove all occurrences in List using While Loop
mylist = [21, 5, 8, 52, 21, 87]
r_item = 21
# remove the item for all its occurrence
while r_item in mylist:
    mylist.remove(r_item)
print(mylist)

执行和输出:
使用 while 循环和 remove() 方法移除.png

7. 列表循环遍历

可以使用 for 循环、while 循环或者枚举对列表中的元素进行循环遍历。接下来我们对其进行逐一介绍。
还是以异构数据类型的那个列表为例。

a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]

7.1. 使用 while 循环遍历

使用 while 循环依次打印列表中的所有项。

# Loop List items using While Loop
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
i = 0
while i < len(a):
    print(a[i])
    print(type(a[i]))
    i += 1

执行和输出:
使用 while 循环遍历.png

7.2. 使用索引遍历列表

for 配合 range 函数,可以通过索引访问遍历列表。

# Loop List items using index
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
for i in range(len(a)):
    print(a[i])

执行和输出:
使用索引遍历列表.png
如果你想在遍历的时候需要使用索引的话可以使用这种方式。

7.3. 增强型 for 循环

或者使用增强型 for 循环无索引直接访问元素本身。

# Loop List items accessing list item directly
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
for x in a:
    print(x)

执行和输出:
增强型 for 循环.png
如果在便利时不需要索引即可使用这种方式。

7.4. 枚举遍历列表元素

使用枚举,可以同时访问元素及其索引。

# Loop List items using Enumerate
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
for i, x in enumerate(a):
    print('element#', i, 'is:', x)

执行和输出:
枚举遍历列表元素.png

8. 统计列表中指定值的项的个数

要统计指定值在列表中出现了多少次,可以使用列表的 count() 含税,以指定值作为参数传递给它。
接下来的示例中我们新建了一个列表,然后查找了一些指定值出现的次数。

# Python – Count the items with a specific value in the List
mylist = [6, 52, 74, 62, 85, 62, 62, 85, 6, 92, 74]
length_74 = mylist.count(74)
length_62 = mylist.count(62)
length_92 = mylist.count(92)
length_73 = mylist.count(73)
print('74 occurred', length_74, 'times in the list')
print('62 occurred', length_62, 'times in the list')
print('92 occurred', length_92, 'times in the list')
print('73 occurred', length_73, 'times in the list')

执行和输出:
统计列表中指定值的项的个数.png
count() 函数只需要一个参数。

9. 将一张列表追加到另一张列表

将一张列表追加到另一张列表,使用列表对象的 extend() 函数。

list1.extend(list2)

其中列表 list2 中的元素将被追加到列表 list1。

9.1. 追加列表到另一个列表

接下来的示例中,我们创建了两张列表,然后将第二张追加到第一张。

# Append a list to another list
list1 = [6, 52, 74, 62]
list2 = [85, 17, 81, 92]
list1.extend(list2)
print(list1)

执行和输出:
追加列表到另一个列表.png
list1 的内容已被修改,list2 的内容被追加到原先元素的后边。## 9.2. 保留原来列表,追加另一张列表
如果你想保留原来列表的内容不被改变,复制该列表到一个变量,然后追加另一张列表到该变量。

# Append a list to another list keeping a copy of original list
list1 = [6, 52, 74, 62]
list2 = [85, 17, 81, 92]
list = list1.copy()
list.extend(list2)
print(list)

执行和输出:
保留原来列表,追加另一张列表.png

10. 查找元素在列表中的索引

将给定值传给列表类的 index() 方法可以查出其在列表中第一次出现的位置。

index = mylist.index(item)

10.1. 查找列表中某项的索引

接下来我们新建了一个装有数字的列表,使用 index() 方法我们找到了元素 8 在列表中的索引。

# Find index when item is present in List
mylist = [21, 5, 8, 52, 21, 87]
item = 8
# search for the item
index = mylist.index(item)
print('The index of', item, 'in the list is:', index)

执行和输出:
查找列表中某项的索引.png
该元素出现在第三个位置,或者说索引为 2。

10.2. 查找列表中某多次出现项的索引

Python 的列表允许同一元素多次出现。这种情况下,只有第一次出现位置的索引会被返回。

# Find index when item is present multiple times in List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 52
# search for the item
index = mylist.index(item)
print('The index of', item, 'in the list is', index)

执行和输出:
查找列表中某多次出现项的索引.png
元素 52 出现了两次,但是只有第一次出现位置的索引被返回了。

10.3. 查找没有出现在列表中的项的索引

如果元素没有出现在列表中,使用 index() 函数你将会得到一个消息为 item is not in list 的 ValueError。

# Find Index when the specided Item is not present in List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 67
# search for the item
index = mylist.index(item)
print('The index of', item, 'in the list is', index)

执行和输出:
查找没有出现在列表中的项的索引.jpg

11. 在指定索引处插入元素

要在指定位置或索引处添加一个元素,你可以使用 Python 内建类 list 的 insert() 方法。

mylist.insert(index, item)

在指定索引 index 处将会插入 item 元素。指定索引后边的元素会依次右移。

11.1. 在指定索引处插入元素

在以下实例中我们新建了一个装有数字的列表,然后我们在索引 4 处插入一个元素 36。

# Insert Item at Specified Index in List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = 4
# insert item in mylist at index
mylist.insert(index, item)
print(mylist)

执行和输出:
在指定索引处插入元素.jpg

11.2. 在列表头插入元素

以下示例我们将在列表的起始位置插入 36。我们需要提供索引 0 给 insert() 方法。

# Insert Item at Start of List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = 0 # 1st position
# insert item in mylist at index
mylist.insert(index, item)
print(mylist)

执行和输出:
在列表头插入元素.jpg

11.3. 在列表尾插入元素

以下示例我们将在列表的结束位置插入 36。我们需要提供索引列表长度给 insert() 方法。

# Insert Item at End of List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = len(mylist)
# insert item in mylist at index
mylist.insert(index, item)
print(mylist)

执行和输出:
在列表尾插入元素.jpg

11.4. 插入数组越界的元素

如果提供给 insert() 方法的索引超出了列表的长度,结果就是将新元素追加到列表尾。
以下是一个提供的索引超出列表长度的例子。

# Insert Item with Index out of Bounds of List
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = 1000 # index out of bounds of list
# insert item in mylist at index
mylist.insert(index, item)
print(mylist)

执行和输出:
插入数组越界的元素.png
相反,如果你提供了一个负值索引,新元素将会插入到列表的起始位置。

mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = -10 # index out of bounds of list
# insert item in mylist at index
mylist.insert(index, item)
print(mylist)

执行和输出:
负值索引,新元素将会插入到列表的起始位置.png

12. 在指定索引处移除元素

要在指定位置或索引处移除某元素,可以使用内建类 list 的 pop() 方法。该方法语法如下:

mylist.pop(index)

其中索引是可选的。如果你没有提供索引,该列表的最后一个元素将会被移除。

12.1. 在指定索引处移除元素

以下示例中我们新建了一个装有数字的列表。我们将会使用 pop() 方法以指定索引 3 移除元素。

# Remove Item at Specific Index from List
mylist = [21, 5, 8, 52, 21, 87, 52]
index = 3
# delete item in mylist at index
mylist.pop(index)
print(mylist)

执行和输出:
在指定索引处移除元素.png
索引为 3 的元素 52 已被移除。

12.2. 移除列表的最后一个元素

要移掉列表的最后一个元素,只需要不传递任何索引给 pop() 方法即可。

# Remove Last Item of List
mylist = [21, 5, 8, 52, 21, 87, 52]
# delete last item in mylist
mylist.pop()
print(mylist)

执行和输出:
移除列表的最后一个元素.png

12.3. 将超出列表长度的索引传递给 pop() 方法

如果你将超出列表长度的一个索引传递给 pop() 方法,你将会得到一个消息为 pop index out of range 的 IndexError。

# pop() method with index > length of list
mylist = [21, 5, 8, 52, 21, 87, 52]
index = 100 # index > length of list
mylist.pop(index)
print(mylist)

执行和输出:
将超出列表长度的索引传递.png

12.4. 将负值索引传递给 pop() 方法

如果你将一个负值作为索引传递给 pop() 方法,该索引将被认为是一个从 1 起始的逆序索引。
比如,如果你提供 -1 作为索引给 pop(),最后一个元素将被移除。
如果你提供 -3 给 pop(),倒数第 3 个元素将被删除。
而如果你提供给索引负数的绝对值大于列表的长度,你同样会得到像上小节示例中的 IndexError。
在接下来的示例中,我们以 -2 为索引给 pop() 方法,倒数第 2 个元素将被移除。

# pop() with negative index
mylist = [21, 5, 8, 52, 21, 87, 52]
index = -2 # index < 0
mylist.pop(index)
print(mylist)

执行和输出:
将负值索引传递.png

13. 列表反转

要反转一张列表里所有元素的排列顺序,或者通俗点将叫列表反转,可以使用内建类 list 的 reverse() 方法。
mylist.reverse()
另一种列表反转的方法是切片。
reversed_list = mylist[::-1]

13.1. 使用 reverse() 反转列表

接下来的示例中,我们创建了一个装有数字的列表。然后我们使用 reverse() 对其进行反转。

# Reverse List using reverse()
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist.reverse()
print(mylist)

执行和输出:
使用 reverse() 反转列表.jpg
可以看出 reverse() 是直接对原始列表进行修改。

13.2. 使用切片反转列表

接下来我们来使用切片反转列表。

# Reverse List using Slicing
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist2 = mylist[ : : -1]
print(mylist)
print(mylist2)

执行和输出:
使用切片反转列表.png
可以看出切片并不修改原列表,只返回一个新的反转后的列表。

13.3. 反转字符串列表

接下来我们将一个装有字符串的列表进行反转。

# Reverse List of Strings
mylist = ['list', 'dict', 'set']
mylist.reverse()
print(mylist)

执行和输出:
反转字符串列表.png

13.4. 列表反转的应用

  • 通过反转列表,你改变了列表中元素的存储次序。如果列表中元素原来已经正序排列,那么通过列表反转,你将得到一个逆序排列。

14. 列表排序

要对列表进行正序或逆序排序,你可以使用内建类 list 的 sort() 方法。

mylist.sort(cmp=None, key=None, reverse=False)

其中,

  • cmp 定义了一个自定义的比较函数,它需要两个参数,返回一个负数,零或正数,这取决于第一个参数比第二个参数小,相等或大。比如:cmp=lambda x,y: cmp(x.lower(), y.lower())
  • key 定义了一个函数,它有一个参数,用于从每个列表元素中提取比较键:key=str.lower。默认值为 None (即直接对元素进行比较)。
  • reverse 是一个布尔值。如果设置为 True,列表元素将会按照比较结果反转排列。

14.1. 对列表正序排序

要对列表进行正序排列,你只需要不传入任何参数地调用列表对象的 sort() 方法。在接下来的示例中,我们新建了一个装有数字的列表,然后我们对其中的元素进行正序排列。

# Sort a List in Ascending Order
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist.sort()
print(mylist)

执行和输出:
对列表正序排序.png
sort() 函数的默认行为是对列表元素进行正序排序。

14.2. 对列表逆序排序

要对列表进行逆序排序,可以传递 reverse=True 参数给 sort() 函数。

# Sort a List in Descending Order
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist.sort(reverse=True)
print(mylist)

执行和输出:
对列表逆序排序.png

15. 找到一张列表中最大的数字

你可以通过使用 sort() 函数或者经典的 for 循环来查找一张列表中最大的那个数字。使用 sort() 函数是一种简洁的方式。但出于学习起见我们还是两种方式都看一下。

15.1. 使用 sort() 函数找到最大数字

通过上一节的学习我们知道 sort() 函数将会把一张列表中的元素按正序或逆序进行排列。在你对列表排序之后,如果你的列表按正序排列那么最大的那个数字会排在列表的最后一个位置,而如果你按逆序排列它将出现在列表的起始位置。

# Find the largest number using sort() function
a = [18, 52, 23, 41, 32]
a.sort()
a_len = len(a)
ln = a[a_len - 1]
print('Largest element is', ln)

执行和输出:
使用 sort() 函数找到最大数字.png

15.2. 使用 for 循环找到最大数字

尽管使用 sort() 函数查找最大数字看起来很简单,但是使用 for 循环查找可以相对更快地执行操作,因为它对列表的操作次数更少。

# Find the largest number using for loop
a = [18, 52, 23, 41, 32]
ln = 0
for i in a:
    if i > ln:
        ln = i
print('Largest element is', ln)

执行和输出:
使用 for 循环找到最大数字.png
在上述示例中,我们新建了一张列表,并假设其最大数字为 0。然后我们使用 for 循环对该列表进行遍历。在每次迭代期间,我们检查该最大数字是否比当前元素小。如果是这样的话,我们将当前元素分配给最大数字。列表遍历结束以后,最大数字参数里放的数字就是列表里最大的那个数。

16. 找到一张列表中最小的数字

你可以通过使用 sort() 函数或者经典的 for 循环来查找一张列表中最小的那个数字。使用 sort() 函数是一种简洁的方式。但出于学习起见我们还是两种方式都看一下。

16.1. 使用 sort() 函数找到最小数字

通过上一节的学习我们知道 sort() 函数将会把一张列表中的元素按正序或逆序进行排列。在你对列表排序之后,如果你的列表按正序排列那么最小的那个数字会排在列表的起始位置,而如果你按逆序排列它将出现在列表的最后位置。

# Find the smallest number using sort() function
a = [18, 52, 23, 41, 32]
a.sort()
sn = a[0]
print('Smallest element is', sn)

执行和输出:
使用 sort() 函数找到最小数字.png

16.2. 使用 for 循环找到最小数字

尽管使用 sort() 函数查找最小数字看起来很简单,但是使用 for 循环查找可以相对更快地执行操作,因为它对列表的操作次数更少。

# Find the smallest number using for loop
a = [18, 52, 23, 41, 32]
sn = float("inf")
for i in a:
    if i < sn:
        sn = i
print('Smallest element is', sn)

执行和输出:
使用 for 循环找到最小数字.png
在上述示例中,我们新建了一张列表,并假设其最小数字为无穷大。然后我们使用 for 循环对该列表进行遍历。在每次迭代期间,我们检查该最小数字是否比当前元素大。如果是这样的话,我们将当前元素分配给最小数字。列表遍历结束以后,最小数字参数里放的数字就是列表里最小的那个数。

参考资料

发布了273 篇原创文章 · 获赞 1324 · 访问量 649万+

猜你喜欢

转载自blog.csdn.net/defonds/article/details/95099787
今日推荐