Python有几种顺序的数据类型,可让您以有组织的高效方式存储数据集合。基本序列类型是字符串,列表,tapple和范围对象。
本文介绍了Python Tapple的基础知识。了解怎样创建taples,访问元素,解开taples等等。
les类似于列表,但是主要区别在于列表是可变的,而tap是不可变的。这意味着在创建元组后就无法对其进行更改。
Tapple既可以存储异构数据,也可以存储同源数据,但通常用于存储异构元素的集合。
创建a头
通过将项目放在一对括号内来创建 []
, 被逗号隔开。它们可以具有许多不同类型的项目。这是一个例子:
colors = ('orange', 'white', 'green')
Taples可以具有混合数据类型的项目。您也可以声明嵌套的taples。这些项目中的另一个是列表,tapple或字典。
my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))
括号之间没有元素的括号表示空的tap。
my_tuple = ()
要创建仅包含一个元素的taple,您需要在该元素之后添加一个逗号。
my_tuple = (1)
type(my_tuple)
my_tuple = (1,)
type(my_tuple)
<class 'int'>
<class 'tuple'>
Taple是 tuple()
构造函数:
colors_list = ['orange', 'white', 'green']
colors_typle = tuple(colors_list)
print(type(colors_typle))
<class 'tuple'>
创建a的另一种方法是使用tapple包装功能。这使您可以从一系列逗号分隔的对象中创建taples。
directions = "North", "South", "East", "West"
print(type(directions))
<class 'tuple'>
访问tapple元素
Taple项目可以通过其索引进行引用。索引是整数 0
至 n-1
哪里 n
件数:
my_tuple = ["a", "b", "c", "d"]
0 1 2 3
在Python中,索引在方括号中指定。
my_tuple[index]
例如,要访问taple的第三个元素: tuple_name[2]
:
directions = ("North", "South", "East", "West")
directions[2]
'East'
当引用不存在的索引时 IndexError
我有一个例外:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
使用多个索引来访问嵌套taples中的项目。
my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))
my_tuple[3][1]
'bar'
您还可以使用负索引来访问taple元素。最后一项叫做 -1
,倒数第二个项目 -2
等等:
my_tuple = ("a", "b", "c", "d")
-4 -3 -2 -1
directions = ("North", "South", "East", "West")
directions[-2]
'East'
le片#
在Python中,您可以使用以下格式对Taples和其他顺序数据类型进行切片:
sequence[start:stop:step]
start
开始提取的索引。如果使用负索引,则表示距锥末端的偏移量。如果省略此参数,那么切片将从索引0开始。stop
提取完成之前的索引。结果不包含“停止”元素。如果使用负索引,则表示距锥末端的偏移量。如果省略此参数或大于其长度,则切片将移至tapple的末尾。step
是一个可选参数,用于指定切片步骤。如果未指定,则默认为1。如果使用负值,则切片将以相反的顺序获取元素。
将切片切成薄片的结果是一个包含提取元素的新tapple。
以下格式在Python中有效。
T[:] # copy whole tuple
T[start:] # slice the tuple starting from the element with index "start" to the end of the tuple.
T[:stop] # slice the tuple starting from the begging up to but not including the element with index "stop".
T[start:stop] # slice the tuple starting from the element with index "start" up to but not including the element with index "stop".
stop"
T[::step] # slice the tuple with a stride of "step"
下面是一个示例,说明怎样从索引1的元素到索引4的元素切片Taple。
vegetables = ('Potatoes', 'Garlic', 'Celery', 'Carrots', 'Broccoli')
vegetables[1:4]
('Garlic', 'Celery', 'Carrots')
开瓶器#
使用Python功能解压缩序列,可让您将序列对象分配给变量。这是一个例子:
colors = ('orange', 'white', 'green')
a, b, c = colors
print(a)
print(b)
print(c)
根据tapple元素位置的值被分配给左侧的变量。
orange
white
green
对抽头进行解压缩时,左侧抽头中的变量数必须与tapple元素的数目相同。除此以外, ValueError
例外。
colors = ('orange', 'white', 'green')
a, b = colors
ValueError: too many values to unpack (expected 2)
当方法或函数返回对象序列时,解压缩很有用。
def square_area_circumference(side_lenght):
return side_lenght * side_lenght, side_lenght * 4
area, circumference = square_area_circumference(5)
print(area)
print(circumference)
25
20
更换水嘴#
Taples是不可变的数据结构,不能直接更新。您无法在抽头中添加,修改或删除元素。
当我尝试更改tapple元素时,得到以下信息: TypeError
例外:
colors = ("orange", "white", "green")
colors[1] = "blue"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
您可以更改可变tapple项的元素。例如,如果将列表作为taple的元素之一,则可以更新列表元素。
my_tuple = (1, 2, [5, 6, 7])
my_tuple[2][1] = 4
print(my_tuple)
(1, 2, [5, 4, 7])
头长度
内建 len()
该函数返回指定对象的项目总数。
要找到锥度的长度,请以其为参数 len()
功能:
len(L)
这是一个例子:
colors = ("orange", "white", "green")
lenght = len(colors)
print(lenght)
3
遍历水龙头#
遍历taple中的所有元素 for
循环:
directions = ("North", "South", "East", "West")
for direction in directions:
print(direction)
North
South
East
West
如果需要索引,则可以自由使用几种方法。最常见的方法是 range()
和 len()
使用功能或内置 enumerate()
功能。
下面的示例演示怎样获取Taple中每个项目的索引和值。
directions = ("North", "South", "East", "West")
for i in range(len(directions)):
print("Index {} : Value {}".format(i, directions[i]))
Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value West
而不是使用 range(len(...))
模式,可以使用 enumerate()
以更类似于Python的方式循环敲击的函数:
directions = ("North", "South", "East", "West")
for index, value in enumerate(directions):
print("Index {} : Value {}".format(index, value))
Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value West
检查元素是否存在
检查抽头中是否存在元素 in
和 not in
操作员:
colors = ("orange", "white", "green")
print("orange" in colors)
输出将是以下之一 True
要么 False
:
True
这是另一个使用示例。 if
声明:
colors = ("orange", "white", "green")
if "blue" not in colors:
print("no")
else:
print("yes")
no
抽头方法#
taple对象接受以下方法:
count(x)
-返回“ x”出现在抽头中的次数。index(x)
-返回值“ x”的元素首次出现的位置。
以下是显示怎样使用该方法的简单示例。
my_tuple = ("a", "s", "s", "q", "a", "n")
print(my_tuple.count('a'))
print(my_tuple.index('a'))
2
0
总结#
在Python中,taples是对象的不可变序列,一旦创建就无法修改。
如果您有任何问题或意见,请随时发表评测。
蟒蛇