Python基础语法-内置数据结构之元组

时间:2022-05-03
本文章向大家介绍Python基础语法-内置数据结构之元组,主要内容包括元组创建及使用、元组常用方法、元组切片操作、命名元组、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

今天给大家讲解Python的内置数据结构元组。前面的内容大家有没有复习呢?

元组的特点:不可变的列表,但是可哈希的。列表是不可哈希的。

元组创建及使用

使用()括起来或使用tuple()创建元组。

如果一个元组只有一个元素,其初始化时应该如下定义:

# 只有一个元素的元组,在括号里需要添加逗号,以表明是元组
>>> t = (1,)
>>> t   
(1,)
>>> type(t)
<class 'tuple'>

>>> t = (1) # 如果只有一个元素,t则变成了int类型;如果要使t为一个元素
            # 的元组,需如下定义
>>> type(t)
<class 'int'>

一个小例子:

t = (1, 2, 3)
>>> type(t)
<class 'tuple'>
t[0]
1
t[0] = 5 # 执行不成功,会报TypeError错误
TypeError: 'tuple' object does not support item assignment
hash(t)
2528502973977326415
>>> t = (1) # 如果只有一个元素,t则变成了int类型;如果要使t为一个元素
            # 的元组,需如下定义
>>> type(t)
<class 'int'>

# 只有一个元素的元组,在括号里需要添加逗号,以表明是元组
>>> t = (1,)
>>> t   
(1,)
>>> type(t)
<class 'tuple'>

>>> t = (1, 2, 3)
>>> len(t)
3

>>> t.index(2)
1
>>> t.count(2)
1

元组示例1:

[root@python ~]# cat fig05_06.py
hour = int(input("Enter hour: "))
minute = int(input("Enter minute: "))
second = int(input("Enter second: "))
currentTime = hour, minute, second   # create tuple
print("The value of currentTime is:", currentTime)
# access tuple
print("The number of seconds since midnight is", 
   (currentTime[0] * 3600 + currentTime[1] * 60 +
     currentTime[2]))

[root@python ~]# python fig05_06.py
Enter hour: 3
Enter minute: 4
Enter second: 5
The value of currentTime is: (3, 4, 5)
The number of seconds since midnight is 11045

示例2:

[root@python ~]# cat fig05_07.py
aString = "abc"
aList = [ 1, 2, 3 ]
aTuple = "a", "A", 1
# unpack sequences to variables
print("Unpacking string...")
first, second, third = aString
print("String values:", first, second, third)
print("nUnpacking list...")
first, second, third = aList
print("List values:", first, second, third)
print("nUnpacking tuple...")
first, second, third = aTuple
print("Tuple values:", first, second, third)
# swapping two values
x = 3
y = 4
print("nBefore swapping: x = %d, y = %d" % (x, y))
x, y = y, x     # swap variables
print("After swapping: x = %d, y = %d" % (x, y))

[root@python ~]# python fig05_07.py
Unpacking string...
String values: a b c

Unpacking list...
List values: 1 2 3

Unpacking tuple...
Tuple values: a A 1

Before swapping: x = 3, y = 4
After swapping: x = 4, y = 3

元组常用方法

index(value) # 默认返回元组中第一次遇到value的索引(从左到右)
count(value) # 计算元组中value出现的次数
嵌套
转换:tuple()

元组切片操作

seq[start:end] => (start:end)

# 从左往右切片,所以start要小于end;否则将得到一个空列表
# start超出索引范围从0开始,end超出范围到len(lst)结束
# start为0时可以省略,end为-1时可以省略
lst = list(range(0, 10))
lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
lst[2:5:2]
[2, 4]
lst[5:2-1]
[5, 4, 3]
# 当step为负数时,从后往前数,此时start应该小于end,否则返回空列表
lst[::-1] # 反转列表
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
lst[0::2]
[0, 2, 4, 6, 8]
lst[1::2]
[1, 3, 5, 7, 9]

命名元组

命名元组与元组类似,也是不可变的。

from collections import namedtuple

User = namedtuple('User', ['name', 'age'])
me = User('lavenliu', 23)
print(me)
print(me.name)
print(me.age)
print(me[0])
print(me[1])
# me.name = 'taoqi'

结果为:

 : User(name='lavenliu', age=23)
 : lavenliu
 : 23
 : lavenliu
 : 23