列表初始化¶

In [1]:
# 空列表
empty_list = []

# 包含元素的列表
int_list = [2,4,5,6,8]
float_list = [3.0,3.14,100.1,99.999]
colors = ['RED','GREEN','BLUE','YELLOW']
bools = [True,False,True,True,False]

# 包含其他数据结构类型的数据
list1 = [[2,3],[4,6]]
list2 = [(3,4,2)]
list3 = [{'name':'Alice'},{'age':18},{'性别':'女'}]

# 包含不同数据类型的元素
mixed_list = [11,3.14,'hello',True,[3,'python'],('a','b','c'),{'fruits':'banana'}]

# 使用内置函数list()创建
numbers = list(range(2,8))

访问列表元素或修改元素¶

In [2]:
mixed_list = [11,3.14,'hello',True,[3,'python'],('a','b','c'),{'fruits':'banana'}]

# 通过切片的方式访问列表中的元素
print(mixed_list[0]) # 访问第一元素,输出结果: 11
print(mixed_list[-1]) # 访问末尾的元素,输出结果: {'fruits': 'banana'}
print(mixed_list[2:5]) # 输出结果: ['hello', True, [3, 'python']]

# 通过索引还可以修改列表
mixed_list[1] = 'modify'
print(mixed_list) # 列表中第2个元素值已修改
11
{'fruits': 'banana'}
['hello', True, [3, 'python']]
[11, 'modify', 'hello', True, [3, 'python'], ('a', 'b', 'c'), {'fruits': 'banana'}]

列表方法¶

list.append(x)¶

在列表末尾添加一个元素,相当于 a[len(a):] = [x]

In [3]:
fruits = ['apple', 'banana', 'orange']
fruits.append('pear')
print(fruits)  # 输出: ['apple', 'banana', 'orange', 'pear']
['apple', 'banana', 'orange', 'pear']

list.extend(iterable)¶

用可迭代对象的元素扩展列表。相当于a[len(a):] = iterable

In [4]:
fruits = ['apple', 'banana', 'orange']
more_fruits = ['pear','cherries']
fruits.extend(more_fruits)
print(fruits) # 输出 ['apple', 'banana', 'orange', 'pear', 'cherries']
['apple', 'banana', 'orange', 'pear', 'cherries']

list.insert(i, x)¶

 在指定位置插入元素。第一个参数是插入元素的索引,因此,a.insert(0, x)在列表开头插入元素,a.insert(len(a), x) 等同于 a.append(x)

In [5]:
fruits = ['apple', 'banana', 'orange']
fruits.insert(0,'pear') # 在开头插入
fruits.insert(len(fruits),'cherries')# 在末尾插入
print(fruits)# 输出 ['apple', 'banana', 'orange', 'pear', 'cherries']
['pear', 'apple', 'banana', 'orange', 'cherries']

list.remove(x)¶

  从列表中删除第一个值为x 的元素。未找到指定元素时,触发 ValueError 异常

In [6]:
fruits = ['apple', 'banana', 'orange']
fruits.remove('orange')
print(fruits) # 输出 ['apple', 'banana']
fruits.remove('pear') #未找到指定元素时,触发 ValueError 异常
print(fruits)
['apple', 'banana']
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[6], line 4
      2 fruits.remove('orange')
      3 print(fruits) # 输出 ['apple', 'banana']
----> 4 fruits.remove('pear') #未找到指定元素时,触发 ValueError 异常
      5 print(fruits)

ValueError: list.remove(x): x not in list

list.pop([i])¶

  删除列表中指定位置的元素,并返回被删除的元素。未指定位置时,a.pop()删除并返回列表的最后一个元素。(方法签名中 i 两边的方括号表示该参数是可选的,不是要求输入方括号。)

In [7]:
fruits = ['apple', 'banana', 'orange','pear']
remove_fruit = fruits.pop(2)
print(remove_fruit)# 输出 orange
print(fruits)# 输出 ['apple', 'banana', 'pear']
orange
['apple', 'banana', 'pear']

list.clear()¶

  删除列表里的所有元素,相当于del a[:] 。

In [8]:
fruits = ['apple', 'banana', 'orange','pear']
fruits.clear()
print(fruits)# 输出 []
[]

list.index(x[, start[, end]])¶

  返回列表中第一个值为 x 的元素的零基索引。未找到指定元素时,触发 ValueError 异常。 可选参数start和 end是切片符号,用于将搜索限制为列表的特定子序列。返回的索引是相对于整个序列的开始计算的,而不是 start 参数。

In [9]:
fruits = ['apple', 'banana', 'orange','pear','cherries','grape']
index_banana = fruits.index('banana') # 
print(f"Index of 'banana': {index_banana}")

index_pear = fruits.index('pear',2) # 从索引2开始查找
print(f"Index of 'pear': {index_pear}")

index_orange = fruits.index('orange',1,4) # 在索引1到4之间查找
print(f"Index of 'pear': {index_pear}")

index_orange1 = fruits.index('orange',3,4) # 错误索引查找
Index of 'banana': 1
Index of 'pear': 3
Index of 'pear': 3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[9], line 11
      8 index_orange = fruits.index('orange',1,4) # 在索引1到4之间查找
      9 print(f"Index of 'pear': {index_pear}")
---> 11 index_orange1 = fruits.index('orange',3,4) # 错误索引查找

ValueError: 'orange' is not in list

list.count(x)¶

  返回列表中元素x 出现的次数。

In [11]:
fruits = ['apple', 'banana', 'orange','pear','cherries','grape','apple','apple']
count_apple = fruits.count('apple')
print(f'苹果在列表中出现了{count_apple}次')
苹果在列表中出现了3次

list.sort(*, key=None, reverse=False)¶

  就地排序列表中的元素

In [12]:
fruits = ['apple', 'banana', 'orange','pear','cherries','grape','apple','apple']
fruits.sort()# 按照字母顺序排序
print(fruits) # 输出 ['apple', 'apple', 'apple', 'banana', 'cherries', 'grape', 'orange', 'pear']
numbers = [4, 2, 1, 3, 5]
numbers.sort()
print(numbers)  # 输出: [1, 2, 3, 4, 5]
['apple', 'apple', 'apple', 'banana', 'cherries', 'grape', 'orange', 'pear']
[1, 2, 3, 4, 5]

list.reverse()¶

  翻转列表中的元素。

In [14]:
fruits = ['apple', 'banana', 'orange','pear']
fruits.reverse()
print(fruits)# 输出 ['pear', 'orange', 'banana', 'apple']
['pear', 'orange', 'banana', 'apple']

list.copy()¶

  返回列表的浅拷贝。相当于a[:]

In [15]:
fruits = ['apple', 'banana', 'orange']
fruits_copy = fruits.copy()
print(fruits_copy)  # 输出: ['apple', 'banana', 'orange']
['apple', 'banana', 'orange']

列表推导式¶

new_list= [expression for item in iterable if condition]

  • expression是对每个元素进行操作的表达式。
  • item 是来自可迭代对象(如列表、字符串等)的元素。
  • condition 是可选的条件,用于过滤元素

基本列表推导式¶

In [16]:
# 生成平方数列表
squares = [x**2 for x in range(5)]
print(squares) # 输出: [0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]
In [17]:
dist = [[-1] * 5 for _ in range(8)]
dist
Out[17]:
[[-1, -1, -1, -1, -1],
 [-1, -1, -1, -1, -1],
 [-1, -1, -1, -1, -1],
 [-1, -1, -1, -1, -1],
 [-1, -1, -1, -1, -1],
 [-1, -1, -1, -1, -1],
 [-1, -1, -1, -1, -1],
 [-1, -1, -1, -1, -1]]

带条件的列表推导式¶

In [18]:
# 生成偶数平方数列表
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # 输出: [0, 4, 16, 36, 64]
[0, 4, 16, 36, 64]

字符串操作列表推导式¶

In [19]:
# 提取字符串中的数字
string = "Hello 123 Python 456"
numbers = [int(x) for x in string if x.isdigit()]
print(numbers) # 输出: [1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

嵌套列表推导式¶

In [20]:
# 生成九九乘法表
multiplication_table = [[i * j for j in range(1, 10)] for i in range(1, 10)]
for l_table in multiplication_table:
    print(l_table)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 8, 10, 12, 14, 16, 18]
[3, 6, 9, 12, 15, 18, 21, 24, 27]
[4, 8, 12, 16, 20, 24, 28, 32, 36]
[5, 10, 15, 20, 25, 30, 35, 40, 45]
[6, 12, 18, 24, 30, 36, 42, 48, 54]
[7, 14, 21, 28, 35, 42, 49, 56, 63]
[8, 16, 24, 32, 40, 48, 56, 64, 72]
[9, 18, 27, 36, 45, 54, 63, 72, 81]

带条件的嵌套列表推导式¶

In [21]:
# 生成过滤偶数的九九乘法表
filtered_table = [[i * j for j in range(1, 10) if (i >= j)] for i in range(1, 10)]
for l_table in filtered_table:
    print(l_table)
# 输出: 一个包含九个列表的列表,每个列表包含符合条件的乘法表元素
[1]
[2, 4]
[3, 6, 9]
[4, 8, 12, 16]
[5, 10, 15, 20, 25]
[6, 12, 18, 24, 30, 36]
[7, 14, 21, 28, 35, 42, 49]
[8, 16, 24, 32, 40, 48, 56, 64]
[9, 18, 27, 36, 45, 54, 63, 72, 81]