Python 列表

Python 列表类似于数组,可以存贮多个元素。列表中数据是有序的,可重复的,列表是可变的。同时列表提供了很多方法方便我们操作列表和其中的元素。

Python 列表类似于数组,可以存贮多个元素。列表中数据是有序的,可重复的,列表是可变的。同时列表提供了很多方法方便我们操作列表和其中的元素。

列表是 Python 中用于存储数据集合的 4 种内置数据类型之一,其他 3 种是元组集合字典

创建 Python 列表可以使用列表字面量(方括号 [])或者 list() 构造函数。

thislist = ["apple", "banana", "apple", "cherry"]
thislist = list(("apple", "banana", "apple", "cherry"))

Python 列表具有如下特征:

  • 列表可以使用索引获取其中的元素,和其他语言一样,列表的索引从 0 开始。
  • 列表中的元素按照插入的顺序保存,新插入列表的元素位于列表的末尾。
  • 列表是可变的。我们可以在创建列表后更改、添加和删除列表中的项目。
  • 列表中元素可以重复存在。
  • 列表中的元素的数据类型可以不同。

列表的类型

Python 列表的数据类型为 <class 'list'>

打印列表的数据类型:

mylist = ["apple", "banana", "cherry"]
print(type(mylist))  # 输出 <class 'list'>

访问列表

列表可以通过方括号中的索引号访问其中的项目。

打印列表的第二项:

thislist = ["apple", "banana", "cherry"]
print(thislist[1])

索引也可以使用负数,负索引是指从最后开始,-1 指最后一项, -2 指倒数第二项等。

打印列表的最后一项:

thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

子列表

可以通过切片语法指定开始索引和结束索引(不包含)返回一个子列表,返回的子列表是一个包含了部分元素的新列表。

返回第三、第四和第五项:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5]) # ['cherry', 'orange', 'kiwi']

省略开始索引,则开始索引为 0; 省略结束索引,则结束索引为最后一个元素的索引。

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4]) # ['apple', 'banana', 'cherry', 'orange']

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[3:]) # ['orange', 'kiwi', 'melon', 'mango']

当索引为负数的时候,是指从最后开始,-1 指最后一项, -2 指倒数第二项等。

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1]) # ['orange', 'kiwi', 'melon']

检查项目是否存在

要确定列表中是否存在指定的项目,请使用 in 关键字:

thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
  print("Yes, 'apple' is in the fruits list")

输出:Yes, 'apple' is in the fruits list

更改单个项目

可以通过索引号直接修改某个索引位置的值为新值。

更改第二项:

thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist) # ["apple", "blackcurrant", "cherry"]

更改多个项目值

可以使用切片语法同时替换列表中的多个项目值。

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

输出: ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']

当给出的项目数与指定的索引范围不匹配时,列表的长度会发生变化:

  • 给出的项目数量多于指定的索引范围时,会插入多出的元素,导致列表长度变长
  • 给出的项目数量少于指定的索引范围时,会插入删除为匹配的索引的元素,导致列表长度变短

可以这么理解,使用切片语法更新列表的多个项目时,首先从列表中删除切片语法的索引范围中的元素,然后再将新的值插入到删除的位置。

看下面的例子:

thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

输出: ['apple', 'blackcurrant', 'watermelon', 'cherry']

thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)

输出: ['apple', 'watermelon']

插入项目

insert() 方法在指定的索引位置插入项目,不替换任何项目。

thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)

输出: ['apple', 'banana', 'watermelon', 'cherry']

追加项目

append() 方法列表的末尾插入新项目。 append() 方法导致列表长度变长。

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

输出: ['apple', 'banana', 'cherry', 'orange']

扩展列表

extend() 方法可以把另一个列表中的元素附加到当前列表的末尾。

thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

输出: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']

extend() 可以追加任何可迭代对象(元组、集合、字典等)。

将元组的元素添加到列表中:

thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

输出: ['apple', 'banana', 'cherry', 'kiwi', 'orange']

删除指定项目

remove() 方法删除指定的项目。

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist) # 输出 ['apple', 'cherry']

删除指定索引

pop() 方法删除指定的索引位置的项目。

thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist) # 输出 ['apple', 'cherry']

如果不指定索引,pop() 方法将删除最后一项。

thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist) # 输出 ['apple', 'banana']

还可以通过 del 关键字删除指定的索引位置的项目。

thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist) # 输出 ['banana', 'cherry']

del 关键字也可以完全删除列表。

thislist = ["apple", "banana", "cherry"]
del thislist

通过 del 关键字删除的变量将会变为未定义,再使用的话会报错。

清空列表

clear() 方法清空列表中的项目。列表仍然存在,但没有内容。

thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist) # 输出 []

遍历列表

遍历列表元素

使用 for 循环遍历列表项:

thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)

输出:

apple
banana
cherry

如有需要,请跳转到 Python For 循环章节中了解有关 for 循环的更多信息。

通过索引遍历列表

使用 range()len() 函数创建包含了索引号的可迭代对象。

通过索引号打印所有项目:

thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
  print(thislist[i])

在上面的例子中创建的可迭代对象是 [0, 1, 2]

使用 While 循环

使用 while 循环遍历列表项。

thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
  print(thislist[i])
  i = i + 1

如有需要,请跳转到 Python While 循环章节中了解有关 while 循环的 更多信息。

列表推导式

当您想要基于现有列表的值创建新列表时,列表推导式 List Comprehension 提供了更短的语法。

例如,从现有一个水果列表的过滤出水果名称中带有字母“a”的水果,并形成一个新列表。

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.append(x)

print(newlist)

使用列表推导式,您只需一行代码即可完成所有操作:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

语法

newlist = [expression for item in iterable if condition]

说明:

  • [] 包围起来,表示返回的是一个列表。
  • iterable 是一个可迭代对象,如列表,元组,集合等。
  • item 是每次循环迭代的列表项目。
  • if condition 是过滤条件,只有符合条件的项目才会留下。
  • expression 是一个表达式,可对 item 进行运算返回一个新的值。
  • 所有符合条件的项目运算后,形成一个新的列表。
  • 返回值是一个新列表,旧列表保持不变。

条件

条件像一个过滤器,只有条件运算结果为 True 的项目才被运算。

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if x != "apple"]

条件 if x != "apple" 过滤掉 “apple” ,使新列表包含除 “apple” 之外的所有水果。

条件是可选的,省略条件则返回所有列表的项目。

没有 if 声明:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits]

可迭代对象

可迭代对象,可以是列表,元组,集合等,也可以使用 range() 函数创建一个可迭代对象。

newlist = [x for x in range(10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

同样的例子,但有一个条件,只接受小于 5 的数字:

newlist = [x for x in range(10) if x < 5] # [0, 1, 2, 3, 4]

表达式

表达式是对当前的迭代项目的运算,表达式的结果成为新列表的一项。

新列表中的值都是大写的:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x.upper() for x in fruits]
print(newlist) # ['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']

您可以将结果设置为您喜欢的任何内容,比如将新列表中的所有值设置为“hello”:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = ['hello' for x in fruits]
print(newlist) # ['hello', 'hello', 'hello', 'hello', 'hello']

表达式还可以是一个条件运算,类似于三目运算符:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x if x != "banana" else "orange" for x in fruits]
print(newlist) # ['apple', 'orange', 'cherry', 'kiwi', 'mango']

上面例子中的表达式说:如果不是 banana,则返回该项目,如果是 banana,则返回 orange。

排序列表

Python 列表的 sort() 方法可以对列表项目进行排序。

按字母数字排序列表

默认情况下,sort() 方法可以按字母数字的升序对列表进行自然排序。

自然排序:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist) # ['banana', 'kiwi', 'mango', 'orange', 'pineapple']

按数字对列表进行排序:

thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist) # [23, 50, 65, 82, 100]

降序排序

要降序排序,请使用关键字参数 reverse = True

按字符串列表降序排序:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist) # ['pineapple', 'orange', 'mango', 'kiwi', 'banana']

对数字列表进行降序排序:

thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist) # [100, 82, 65, 50, 23]

键函数

除了内置的比较规则,还可以使用键函数 key = function 自定义各个项目的比较基准。键函数对每个列表项目都会调用一次,实际比较的是键函数的运算结果。

根据数字与 50 的接近程度对列表进行排序:

def myfunc(n):
  return abs(n - 50)

thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist) # [50, 65, 23, 82, 100]

不区分大小写的排序

默认情况下,sort() 方法区分大小写,导致所有大写字母都排在小写字母之前:

区分大小写的排序可能会产生意想不到的结果:

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist) # ['Kiwi', 'Orange', 'banana', 'cherry']

前面用到的键函数可以解决这个问题。如果你想要一个不区分大小写的排序函数,使用 str.lower 作为键函数。

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist) # ['banana', 'cherry', 'Kiwi', 'Orange']

反转列表

reverse() 方法按照列表的当前排序顺序反转元素。

颠倒列表项的顺序:

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist) # ['cherry', 'Kiwi', 'Orange', 'banana']

复制列表

copy() 方法可以复制出当前列表的一个副本,返回一个新的列表。

thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist) # ['apple', 'banana', 'cherry']

连接列表

在 Python 中有多种方法可以连接或连接两个或多个列表,最简单的方法是使用 + 运算符。

连接两个列表:

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2
print(list3) # ['a', 'b', 'c', 1, 2, 3]

使用 + 运算符连接列表会返回一个新的列表,不会影响原有的列表。