Python数据结构: 列表(List)详解

在这里插入图片描述

  在Python中,列表(List)是一种有序、可变的数据类型,被广泛用于存储和处理多个元素。列表是一种容器,可以包含任意数据类型的元素,包括数字字符串列表字典等。本文将深入讨论列表的各个方面,包括基本语法、常见操作,以及实际应用场景。将覆盖列表的创建访问修改列表推导式嵌套列表推导式等关键内容。

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))

2.访问列表元素或修改元素

  通过索引可以访问和修改列表元素,索引从0开始,同时支持负索引从列表末尾访问列表中的元素。

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个元素值已修改

3.列表方法

  列表支持很多方法:
在这里插入图片描述

3.1 list.append(x)

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

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

3.2 list.extend(iterable)

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

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

3.3 list.insert(i, x)

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

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

3.4 list.remove(x)

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

fruits = ['apple', 'banana', 'orange']
fruits.remove('orange')
print(fruits) # 输出 ['apple', 'banana']
fruits.remove('pear') #未找到指定元素时,触发 ValueError 异常
print(fruits)

  运行结果:
在这里插入图片描述

3.5 list.pop([i])

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

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

3.6 list.clear()

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

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

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

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

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) # 错误索引查找

  运行结果:
在这里插入图片描述

3.8 list.count(x)

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

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

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

  就地排序列表中的元素

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]

3.10 list.reverse()

  翻转列表中的元素。

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

3.11 list.copy()

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

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

4.列表推导式

4.1 语法

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

4.2 示例

1) 基本列表推导式

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

2) 带条件的列表推导式

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

3) 字符串操作列表推导式

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

4) 嵌套列表推导式

# 生成九九乘法表
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)
# 输出: 一个包含九个列表的列表,每个列表表示乘法表的一行

  运行结果:
在这里插入图片描述

5)带条件的嵌套列表推导式

# 生成过滤偶数的九九乘法表
filtered_table = [[i * j for j in range(1, 10) if (i * j) % 2 == 0] for i in range(1, 10)]
for l_table in filtered_table:
    print(l_table)
# 输出: 一个包含九个列表的列表,每个列表包含符合条件的乘法表元素

  运行结果:
在这里插入图片描述
在这里插入图片描述

  • 8
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python数据结构与算法分析是一个专栏,主要记录了如何使用Python学习数据结构与算法的笔记和练习题。这个专栏包括了Python的内置数据结构和扩展数据结构Python给我们提供了很多现成的数据结构类型,如列表、元组、字典等,这些是系统预先定义好的数据结构。而还有一些数据组织方式需要我们自己去定义和实现,比如栈、队列等,这些被称为Python的扩展数据结构。通过学习这些数据结构和算法分析,可以更好地理解和应用Python编程语言。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [【Python数据结构与算法】(一)基本概念和算法分析](https://blog.csdn.net/weixin_45052363/article/details/125099029)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* [Python 数据结构与算法详解](https://blog.csdn.net/qq_35029061/article/details/127561227)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

snail哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值