前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python基础语法-内置数据结构之元组

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

作者头像
TestOps
发布2022-04-02 16:37:30
2570
发布2022-04-02 16:37:30
举报
文章被收录于专栏:TestOps云层TestOps云层
元组的特点:不可变的列表,但是可哈希的。列表是不可哈希的。

元组创建及使用

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

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

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

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

一个小例子:

代码语言:javascript
复制
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:

代码语言:javascript
复制
[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:

代码语言:javascript
复制
[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

元组常用方法

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

元组切片操作

代码语言:javascript
复制
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]

命名元组

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

代码语言:javascript
复制
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'

结果为:

代码语言:javascript
复制
 : User(name='lavenliu', age=23)
 : lavenliu
 : 23
 : lavenliu
 : 23

Python基础语法-内置数据结构之列表

Python基础语法-流程控制

Python基础语法-常量与变量

Python开发环境准备

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-10-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 TestOps 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 元组创建及使用
  • 元组常用方法
  • 元组切片操作
  • 命名元组
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档