Python列表:简明教程

图片[1]-Python列表:简明教程-山海云端论坛

引言

在Python中,列表(List)是最常用的数据类型之一。本文汇总了列表相关的常见函数和操作,以便大家查漏补缺。废话少说,让我们直接开始吧!

创建列表

通常我们使用中括号来创建列表:

<code>list1 = []</code>

当然,我们也可以创建包含初始值的列表:

<code>list1 = [1, 2, 3]</code>

列表中可以包含任何数据类型的元素,例如:

<code>list1 = [1, 2, 3] list2 = [3.14, 2.718] list3 = ["apple", "orange"] list4 = [True, [], None, {}] # 所有的数据类型都是有效的</code>

计算列表长度

列表的长度是指列表中包含的元素数量。可以使用内置函数 len 来获取列表的长度:

<code>list1 = ["apple", "orange", "pear"] x = len(list1) # x 的值将为 3</code>

列表元素索引

假设我们有一个包含多个字符串的列表:

<code>list1 = ["apple", "orange", "pear"]</code>

列表中每个字符串都位于某个特定的位置(索引):

  • “apple” 是列表中的第一个元素,索引值为 0
  • “orange” 是列表中的第二个元素,索引值为 1
  • “pear” 是列表中的第三个元素,索引值为 2

我们可以通过索引来访问列表中的元素,例如:

<code>x = list1[0] # x 的值将为 "apple"</code>

同时,索引也可以是负数,表示从列表末尾开始计数:

<code>x = list1[-1] # -1 表示倒数第一个元素,x 的值将为 "pear" y = list1[-2] # -2 表示倒数第二个元素,y 的值将为 "orange"</code>

列表尾部添加新元素

向列表中添加新元素有两种方式,一种是往列表尾部添加新的元素,另一种是往列表特定位置添加新的元素。我们来一一介绍。

假设我们有如下列表:

<code>list1 = ["apple", "orange", "pear"]</code>

如果需要在列表尾部添加新的元素 “durian”,可以使用 append 方法:

<code>list1.append("durian") # list1 现在为 ["apple", "orange", "pear", "durian"]</code>

列表特定位置添加新元素

如果不希望在列表尾部添加元素 “durian”,而是希望在索引位置 2 处插入,可以使用 insert 方法:

<code>list1.insert(2, "durian") # list1 现在为 ["apple", "orange", "durian", "pear"]</code>

更新列表中的元素

假设我们有如下列表:

<code>list1 = ["apple", "orange", "pear"]</code>

如果希望将列表中第一个元素即索引值为 0 的元素替换为 “pineapple”,可以进行如下操作:

<code>list1[0] = "pineapple" # list1 现在为 ["pineapple", "orange", "pear"]</code>

删除列表中的元素

假设我们有如下列表:

<code>list1 = ["apple", "orange", "pear"]</code>

如果希望将列表中第二个元素即索引值为 1 的元素 “orange” 进行删除,可以使用 del 关键字:

<code>del list1[1] # list1 现在为 ["apple", "pear"]</code>

遍历列表

如果需要对列表进行遍历访问,可以使用 for 循环,例如:

<code>list1 = ["apple", "orange", "pear"] for fruit in list1: print(fruit)</code>

同时,也可以通过 range 函数和索引来遍历列表,例如:

pythonCopy code

<code>for i in range(len(list1)): fruit = list1[i] print(i, fruit)</code>

判断列表中包含某元素

可以使用 in 操作符来判断列表中是否包含某个元素,例如:

pythonCopy code

<code>list1 = ["apple", "orange", "pear"] if "apple" in list1: print("apple 在 list1 中") else: print("apple 不在 list1 中")</code>

获取列表中某元素的索引

如果需要获取列表中某元素的索引,可以使用 index 方法,例如:、

<code>list1 = ["apple", "orange", "pear"] i = list1.index("orange") # i 的值将为 1,因为 "orange" 在列表中的索引为 1</code>

需要注意,index 方法返回第一个找到的索引,如果列表中有多个相同的元素,将返回第一个元素的索引。

同时,如果获取列表中不存在的元素的索引时,将会触发错误。

获取列表中某元素出现的次数

假设我们有如下数字列表:

<code>list1 = [4, 5, 6, 4, 4, 5, 6]</code>

如果需要获取列表中元素 4 在列表 list1 中出现的次数,可以使用 count 方法:

<code>x = list1.count(4) # x 的值将为 3,因为 4 在列表中出现了 3 次</code>

总结

本文重点介绍了Python中列表的常见操作和应用场景,并给出了相关的代码示例。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容