python_元祖

一.元组的定义

•- 定义空元组
tuple = ()
•- 定义单个值的元组
tuple = (fentiao,)
•- 一般的元组
tuple = (fentiao, 8, male)
t = tuple()
工厂方法


In [1]: a = ()

In [2]: type(a)
Out[2]: tuple
In [5]: b = ("hello",)   #定义单个元祖的时候,一定要在这个元素后面加逗号

In [6]: type(b)
Out[6]: tuple
In [8]: c = ("hello","world","8") 
In [16]: t = tuple()

In [17]: t
Out[17]: ()

In [18]: print t
()



二.元组的操作


元组也属于序列,可执行的操作如下:
索引、切片、重复、连接和查看长度


1.重复

In [19]: t = (1,2,3)

In [20]: t
Out[20]: (1, 2, 3)

In [21]: a = t*2

In [22]: a
Out[22]: (1, 2, 3, 1, 2, 3)


2.连接

In [23]: t1 = ("hello","world")

In [24]: t2 = ("zl","xian")

In [25]: print t1+t2
('hello', 'world', 'zl', 'xian')

3.查看长度

In [27]: len(t1)
Out[27]: 2

In [28]: len(t)
Out[28]: 3


4.索引

In [32]: t = ("zl",18,"class1")

In [33]: print t[0]  ##正向索引

In [34]: print t[-1]   ##反向索引
class1

5.嵌套的访问

In [35]: t1 = ("zl",18,"class1",("play1","play2","play3"))

In [36]: print t1[3][1]
play2


6.切片

In [37]: t
Out[37]: ('zl', 18, 'class1')

In [38]: print t[:2]  ##切片
('zl', 18)

In [39]: print t[::-1]   ##逆转元组内元素
('class1', 18, 'zl')

7.成员操作符

allow_ips = ('172.25.254.1','172.25.254.2','172.25.254.3')
if "172.25.254.1" in allow_ips:
	print "有访问权限"
else:
	print "无访问权限"


三.元祖的循环

元祖目前接触的第三个可迭代对象
端口扫描器的雏形

ips = ('172.25.254.1','172.25.254.2','172.25.254.3')
ports = (80,8080,21,22)
for ip in ips:
    for port in ports:
        print "[+] Scaning %s:%d" %(ip,port)
In [28]: for ip in allow_ips:
   ....:     for port in ports:
   ....:         print "[+] Scaning %s:%d" %(ip,port)
   ....:         
[+] Scaning 172.25.254.1:80
[+] Scaning 172.25.254.1:8080
[+] Scaning 172.25.254.1:21
[+] Scaning 172.25.254.1:22
[+] Scaning 172.25.254.2:80
[+] Scaning 172.25.254.2:8080
[+] Scaning 172.25.254.2:21
[+] Scaning 172.25.254.2:22
[+] Scaning 172.25.254.3:80
[+] Scaning 172.25.254.3:8080
[+] Scaning 172.25.254.3:21
[+] Scaning 172.25.254.3:22



四.元组可用的内置方法

In [40]: print cmp(('a',1,2,3,4),(1,2))
1
In [41]: print max((12,34,56,78))
78

In [42]: print min((12,34,56,78))
12

#!/usr/bin/env python
#coding:utf-8
'''
枚举
'''

ips = ('172.25.254.1','172.25.254.2','172.25.254.3')
for i,j in enumerate(ips):
    print i,j


(练习)

#!/usr/bin/env python
#coding:utf-8

'''
自动贩卖机雏形
'''

goods = (
    ("Apple",2),
    ("Ipad",4000),
    ("Iwatch",3500)
)
print "商品编号\t商品名称\t商品价格"
for index,value in enumerate(goods):
    print "%3d\t%s%.2f" %(index,value[0],value[1])
                                            



五.元祖的常用方法

• t.count(value)-->int

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

• t.index(value)

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






























  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值