Python数据类型-元组

5、元组(Tuple)

元组和列表类似,不同之处是元组用()将元素扩起来,而列表是用[];其次,列表中的元素可以修改,而元组是不可变的一种数据类型,里面的元素不可更改(不能直接排序、删除、赋值等)。

5.1、创建元组

和列表类似,创建一个元组,只需要用()将元素扩起来,元素之间用逗号,间隔即可。

# example:
tup01 = (1, 2, 3, 4, 5, 6)
tup02 = ('hello', 'good', 'fine', 'thanks')
tup03 = ("desk", "chair", "book", "cup")
tup04 = ()
tup05 = (50,)
tup06 = (50)
tup07 = ('Kevin')
print('tup01 = {}'.format(tup01))
print('tup02 = {}'.format(tup02))
print('tup03 = {}'.format(tup03))
print('tup04 = {}'.format(tup04))
print('tup05 = {},type(tup05):{}'.format(tup05,type(tup05)))
print('tup06 = {},type(tup06):{}'.format(tup06,type(tup06)))
print('tup07 = {},type(tup07):{}'.format(tup07,type(tup07)))
# 运行结果:
tup01 = (1, 2, 3, 4, 5, 6)
tup02 = ('hello', 'good', 'fine', 'thanks')
tup03 = ('desk', 'chair', 'book', 'cup')
tup04 = ()
tup05 = (50,),type(tup05):<class 'tuple'>
tup06 = 50,type(tup06):<class 'int'>
tup07 = Kevin,type(tup07):<class 'str'>
5.2、读取元组的值

和列表相同,元组也是通过下标索引来访问其中的元素。
元组的切片也和列表及字符串的相同,元组名[头下标:尾下标:步长]

# example:
tup01 = ('hello', 'good', 'fine', 'thanks')
print('tup01[0] = {},tup01[2] = {},tup01[-1] = {}'.format(tup01[0], tup01[2], tup01[-1]))
print('tup01[0:2] = {}'.format(tup01[0:2]))
print('tup01[:-1] = {}'.format(tup01[:-1]))
print('tup01[0:] = {}'.format(tup01[0:]))
print('tup01[-2:-1] = {}'.format(tup01[-2:-1]))
# 运行结果:
tup01[0] = hello,tup01[2] = fine,tup01[-1] = thanks
tup01[0:2] = ('hello', 'good')
tup01[:-1] = ('hello', 'good', 'fine')
tup01[0:] = ('hello', 'good', 'fine', 'thanks')
tup01[-2:-1] = ('fine',)
5.3、更新元组的值

元组中的元素是不能修改的,但是我们可以将两个元组连起来变成一个新的元组,还可以对元组执行*操作。

# example:
tup01 = (1, 2, 3, 4, 5, 6)
tup02 = ('hello', 'good', 'fine', 'thanks')
tup03 = ("desk", "chair", "book", "cup")
tup04 = ()
tup05 = (50,)
tup06 = tup02 + tup03
tup07 = tup01 + tup03 + tup05
tup08 = tup02 * 2
print('“tup02 + tup03”后的元组tup06 = {}'.format(tup06))
print('“tup01 + tup03 + tup05”后的元组tup07 = {}'.format(tup07))
print('“tup02 * 2”后的元组tup08 = {}'.format(tup08))
# 运行结果:
“tup02 + tup03”后的元组tup06 = ('hello', 'good', 'fine', 'thanks', 'desk', 'chair', 'book', 'cup')
“tup01 + tup03 + tup05”后的元组tup07 = (1, 2, 3, 4, 5, 6, 'desk', 'chair', 'book', 'cup', 50)
“tup02 * 2”后的元组tup08 = ('hello', 'good', 'fine', 'thanks', 'hello', 'good', 'fine', 'thanks')
5.4、删除元组

因为元组是不可修改的序列,因此不能通过del命令来删除元组中的元素。
只能通过使用del命令来删除整个元组,删除后的元组将不能执行print,会提示元组没有定义。

# example:
tup01 = (1, 2, 3, 4, 5, 6)
del tup01
print(tup01)
# 运行结果:
Traceback (most recent call last):
  File "D:/Python_Project/Temp.py", line 533, in <module>
    print(tup01)
NameError: name 'tup01' is not defined
5.5、元组的函数

a、len():

def len(*args, **kwargs): # real signature unknown
    """ Return the number of items in a container. """
    pass
def len(*args, **kwargs): # real signature unknown
    """ 返回元组中元素的个数。"""
    pass
# example:
tup01 = (1, 2, 3, 4, 5, 6)
print('len(tup01) = {}'.format(len(tup01)))
# 运行结果:
len(tup01) = 6

b、max():

def max(*args, key=None): # known special case of max
    """
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty.
    With two or more arguments, return the largest argument.
    """
    pass
def max(*args, key=None): # known special case of max
    """
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    使用单个可迭代参数,返回其最大的项。默认的关键字参数指定了当提供的iterable为空时返回的对象。
    使用两个或多个参数,返回最大的参数。
    """
    pass
# example:
tup01 = (1, 2, 3, 4, 5, 6)
print('max(tup01) = {}'.format(max(tup01)))
# 运行结果:
max(tup01) = 6

c、min():

def min(*args, key=None): # known special case of min
    """
    min(iterable, *[, default=obj, key=func]) -> value
    min(arg1, arg2, *args, *[, key=func]) -> value
    With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty.
    With two or more arguments, return the smallest argument.
    """
    pass
def min(*args, key=None): # known special case of min
    """
    min(iterable, *[, default=obj, key=func]) -> value
    min(arg1, arg2, *args, *[, key=func]) -> value
    使用单个可迭代参数,返回其最小的项。默认的关键字参数指定了当提供的iterable为空时返回的对象。
    对于两个或多个参数,返回最小的参数。
    """
    pass
# example:
tup01 = (1, 2, 3, 4, 5, 6)
print('min(tup01) = {}'.format(min(tup01)))
# 运行结果:
min(tup01) = 1

d、tuple():

    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass
    def __new__(*args, **kwargs): # real signature unknown
        """ 创建并返回一个新对象。请参阅帮助(类型)以获得准确的签名。"""
        pass
# example:
list01 = [1, 2, 3, 4, 5, 6]
tup01 = tuple(list01)
print('list01 = {},type(list01):{}'.format(list01,type(list01)))
print('tup01 = {},type(tup01):{}'.format(tup01,type(tup01)))
# 运行结果:
list01 = [1, 2, 3, 4, 5, 6],type(list01):<class 'list'>
tup01 = (1, 2, 3, 4, 5, 6),type(tup01):<class 'tuple'>
5.6、小结

元组(tuple)和列表(list)一样是一种Python序列,不同的是,元组中的元素不能修改,元组是一种不可更改的数据类型。
除此之外,元组中元素的访问、切片、截取、合并、求最大值、最小值、长度等都和列表的用法一样。
如果需要更改元组中的元素,可以先讲元组转变成列表,然后改变列表中的元素,然后再将修改过的列表更改成元组。

# example:
tup01 = ('How', 'do', 'you', 'do')
print('tup01 = {}'.format(tup01))
list01 = list(tup01)
print('list01 = {}'.format(list01))
list01.append('!')
print('list01 = {}'.format(list01))
list01.insert(1,'Kevin')
print('list01 = {}'.format(list01))
list01[2] = 'are'
print('list01 = {}'.format(list01))
tup01 = tuple(list01)
print('tup01 = {}'.format(tup01))
# 运行结果:
tup01 = ('How', 'do', 'you', 'do')
list01 = ['How', 'do', 'you', 'do']
list01 = ['How', 'do', 'you', 'do', '!']
list01 = ['How', 'Kevin', 'do', 'you', 'do', '!']
list01 = ['How', 'Kevin', 'are', 'you', 'do', '!']
tup01 = ('How', 'Kevin', 'are', 'you', 'do', '!')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355