Python 列表操作指南1

发布时间 2023-10-03 20:23:43作者: 小万哥丶

Python 列表

mylist = ["apple", "banana", "cherry"]

列表用于在单个变量中存储多个项目。列表是 Python 中的 4 种内置数据类型之一,用于存储数据集合,其他 3 种分别是元组(Tuple)、集合(Set)和字典(Dictionary),它们具有不同的特性和用途。

使用方括号创建列表:

# 创建一个列表
thislist = ["apple", "banana", "cherry"]
print(thislist)

列表项是有序的、可变的,并且允许重复值。列表项具有索引,第一项的索引为[0],第二项的索引为[1],依此类推。

  • 有序:当我们说列表是有序时,意味着项目有一个定义的顺序,而且该顺序不会改变。
  • 可变:列表是可变的,这意味着我们可以在创建列表后更改、添加和删除项目。
  • 允许重复:由于列表具有索引,所以列表可以包含具有相同值的项目。
# 列表允许重复值
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)

列表长度:要确定列表中有多少项,请使用 len() 函数:

# 打印列表中的项目数
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

列表项 - 数据类型,列表项可以是任何数据类型:

# 字符串、整数和布尔数据类型
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

列表可以包含不同的数据类型:

# 包含字符串、整数和布尔值的列表
list1 = ["abc", 34, True, 40, "male"]

type() 函数,从 Python 的角度来看,列表被定义为具有数据类型 'list' 的对象:

# 列表的数据类型
mylist = ["apple", "banana", "cherry"]
print(type(mylist))

列表构造函数,在创建新列表时,也可以使用 list() 构造函数。

# 使用 list() 构造函数创建列表
thislist = list(("apple", "banana", "cherry"))  # 注意双重圆括号
print(thislist)

改变项目的值,要更改特定项目的值,请引用索引编号:

示例,更改第二个项目:

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

要更改特定范围内项目的值,请定义一个具有新值的列表,并引用要插入新值的索引范围:

示例:使用值 "banana" 和 "cherry" 替换值 "blackcurrant" 和 "watermelon":

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

如果插入的项目数量多于替换的项目数量,则新项目将插入到您指定的位置,并且其余项目将相应移动:

示例,通过用两个新值替换它来更改第二个值:

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

注意:当插入的项目数量与替换的项目数量不匹配时,列表的长度将发生变化。如果插入的项目数量少于替换的项目数量,则新项目将插入到您指定的位置,并且其余项目将相应移动:

示例,通过用一个新值替换第二个和第三个值来更改:

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

要插入一个新的列表项,而不替换任何现有值,我们可以使用 insert() 方法。insert() 方法在指定的索引处插入一个项目:

示例,将 "watermelon" 插入为第三个项目:

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

要将项目添加到列表的末尾,请使用 append() 方法:

示例,使用 append() 方法追加项目:

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

要在指定的索引处插入列表项,请使用 insert() 方法。insert() 方法将项目插入到指定的索引位置:

示例,将项目插入为第二个位置:

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

注意:由于上面的示例,列表现在将包含 4 个项目。要将另一个列表中的元素附加到当前列表中,请使用 extend() 方法。

示例,将 tropical 中的元素添加到 thislist 中:

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

这些元素将被添加到列表的末尾。,添加任何可迭代对象extend() 方法不仅限于附加列表,您可以添加任何可迭代对象(元组、集合、字典等)。

最后

为了方便其他设备和平台的小伙伴观看往期文章,链接奉上:

公众号搜索Let us Coding知乎开源中国CSDN思否掘金InfoQ简书博客园慕课51CTOhelloworld腾讯开发者社区阿里开发者社区

看完如果觉得有帮助,欢迎点赞、收藏关注