Python 中的序列数据类型是什么?

pythonprogrammingserver side programming更新于 2023/12/6 19:35:00

序列数据类型用于在 Python 计算机语言中的容器中存储数据。用于存储数据的不同类型的容器是列表、元组和字符串。列表是可变的,可以保存任何类型的数据,而字符串是不可变的,只能存储 str 类型的数据。元组是不可变的数据类型,可以存储任何类型的值。

列表

顺序数据类型类包括列表数据类型。列表是顺序类别中唯一可变的数据类型。它可以存储任何数据类型的值或组件。列表中的许多过程都可以更改和执行,例如附加、删除、插入、扩展、反转、排序等。我们还有更多内置函数来操作列表。

示例

在下面的示例中,我们将了解如何创建列表以及如何使用索引访问列表中的元素。这里我们使用了正常索引和负索引。负索引表示从末尾开始,-1 表示最后一项,-2 表示倒数第二项,依此类推。

List = ["Tutorialspoint", "is", "the", "best", "platform", "to", "learn", "new", "skills"] print(List) print("Accessing element from the list") print(List[0]) print(List[3]) print("Accessing element from the list by using negative indexing") print(List[-2]) print(List[-3])

输出

上述代码产生以下结果

['Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills']
Accessing element from the list
Tutorialspoint
best
Accessing element from the list by using negative indexing
new
learn

字符串

字符串值使用字符串数据类型存储。我们无法操作字符串中的元素,因为它是不可变的。字符串有很多内置函数,我们可以使用它们来做很多事情。以下是一些内置字符串函数 count、isupper、islower、spilt、join 等。

在 Python 中,可以使用单引号、双引号甚至三引号来创建字符串。通常,我们使用三引号来创建多行字符串。

示例

在下面的示例中,我们将了解如何创建字符串以及如何使用索引访问字符串的字符。字符串还支持负索引。

String = "Tutorialspoint is the best platform to learn new skills" print(String) print(type(String)) print("Accessing characters of a string:") print(String[6]) print(String[10]) print("Accessing characters of a string by using negative indexing") print(String[-6]) print(String[-21])

输出

上述代码产生以下结果

Tutorialspoint is the best platform to learn new skills
<class 'str'>
Accessing characters of a string:
a
o
Accessing characters of a string by using negative indexing
s
m

元组

元组是一种属于序列数据类型类别的数据类型。它们类似于 Python 中的列表,但它们具有不可变的属性。我们无法更改元组的元素,但我们可以对它们执行各种操作,例如计数、索引、类型等。

在 Python 中,元组是通过放置用"逗号"分隔的值序列来创建的,可以使用或不使用括号进行数据分组。元组可以有任意数量的元素和任何类型的数据(如字符串、整数、列表等)。

示例

在下面的示例中,我们将了解如何创建元组以及如何使用索引访问元组的元素。元组还支持负索引。

tuple = ('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills') print(tuple) print("Accessing elements of the tuple:") print(tuple[5]) print(tuple[2]) print("Accessing elements of the tuple by negative indexing: ") print(tuple[-6]) print(tuple[-1])

输出

上述代码产生以下结果。

('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills')
Accessing elements of the tuple:
to
the
Accessing elements of the tuple by negative indexing: 
best
skills

相关文章