首页 > 编程语言 > 详细

[python学习笔记]元组

时间:2019-06-04 11:26:09      阅读:99      评论:0      收藏:0      [点我收藏+]

元组

带了紧箍咒的列表

元组和列表不同在于元组为不可变数据类型,它没有append等方法,存储数据更安全

创建方法

tu=(1,2,3,4)

注:单个元组定义必须在后面加逗号,如tu=(1,)

工厂方法:t=tuple([1,2,3])

元组的操作

元组也属于序列:

支持索引、切片、拼接、重复、成员操作符

In [14]: t=(1,2,3)*2
In [15]: t
Out[15]: (1, 2, 3, 1, 2, 3)


In [17]: t1=(hello,one)
In [18]: t2=(hello,two)
In [19]: t1 + t2
Out[19]: (hello, one, hello, two)

元组特性:

对元组分别赋值,引申对多个变量也可以通过元组方式分别赋值

In [20]: t=(vaon,10,male)

In [21]: name,age,gender = t

In [23]: print name,age,gender
vaon 10 male

修改元组:

元组中的元素值是不允许修改的,但我们可以对元组进行连接组合

In [33]: t1=(1,2,3)

In [34]: t2=(a,b,c)

In [35]: t3 = t1 + t2

In [36]: print t3
(1, 2, 3, a, b, c)

删除元组:

元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组

In [30]: t = (ecs,evs,vbs)

In [31]: del t

In [32]: print t
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-32-72ca88a82da5> in <module>()
----> 1 print t

NameError: name t is not defined

元组的方法

t.index(value)

返回value在元组中的偏移量(即索引值)

实例:在t元组中索引2~7之间,打印出值为bool类型的元素的索引值

#!/usr/bin/env python
# coding:utf-8
t=(1,2,3,4,True,False,a,[1,2,3])
for i in t:
  if type(i) == bool:
    print t.index(i,2,7)

 

执行结果:

[root@centos01 python]# python check_bool.py 
4
5

 

t.count(value)-->int

返回value在元组中出现的次数

内置函数

cmp

len

max

min

enumerate

zip

 

[python学习笔记]元组

原文:https://www.cnblogs.com/vaon/p/10972383.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!