python 元组
(一)元组(带了紧箍咒的列表)
元组的创建:
(1)通过赋值方式创建元组;
(2)通过工厂方法创建元组 ####重要
tuple
可以把元组看作一个容器,任何数据类型都可以放在这个容器里面;
t = (1, 1.0, 2j, True, (1,2,3))
print t
t = (1)
print type(t)
定义单个元组,一定要在这个元素后面加逗号
t1 = (1,)
print type(t1)
In[15]:
工厂方法
t = tuple( )
print type(t)
## 元组的操作
1 索引
2切片
3 连接
4重复
5成员操作符 ###重要!
t = (“fentiao”, 5, “male”)
正向索引
print t[0]
反向索引
print t[-1]
元组嵌套时元素的访问
t1 = (“fentiao”, 5, “male”, (“play1”, “play2”, “play3”) )
print t1[3][1]
切片
print t[:2]
逆转元组元素
print t[::-1]
连接
print t + t1
重复
t*3
成员操作符
allow_ips = (‘172.25.254.1’, ‘172.25.254.12’, ‘172.25.254.13’)
if “172.25.254.1” in allow_ips:
print “有访问权限”
else:
print “无访问权限”
## 元组的循环
字符串的循环:
可迭代对象
for i in “hello”:
print i
元组目前接触的第三个可迭代对象;
allow_ips = (‘172.25.254.1’, ‘172.25.254.12’, ‘172.25.254.13’)
for ip in allow_ips:
print ip
### Demo: 端口扫描器雏形
ips = (‘172.25.254.1’, ‘172.25.254.12’, ‘172.25.254.13’)
ports = (80, 8080, 21, 22)
依次读取需要扫描的ip;
for ip in ips:
# 依次读取要扫描的端口
for port in ports:
print “[+] Scaning %s:%d” %(ip, port)
## 元组可用的内置方法
print cmp((‘a’, 1,2,3,4), (1, 2,))
print max((12,34,12,56))
print min((12,34,12,56))
枚举
ips = (‘172.25.254.1’, ‘172.25.254.12’, ‘172.25.254.13’)
for i,j in enumerate(ips):
print i,j
In[63]:
zip:
username = (“user1”, “user2”, “user3”)
password = (“123”, “456”, “789”)
zip(username, password)
### 自动售货系统部分代码
In[60]:
枚举的使用
goods = (
(“Apple”, 2),
(“Ipad”, 4000),
(“iWatch”, 3500)
)
print “商品编号\t商品名称\t商品价格”
for index, value in enumerate(goods):
print “%.3d\t%s\t%.2f” %(index, value[0], value[1])
## 元组的常用方法
In[61]:
t = (2, 1, 1, 2)
print t.count(1)
print t.index(1)