1. Data structure of the list building stack:
Features of the stack: Advanced back-out
#!/usr/bin/env python#coding:utf-8 stack = []info = """ 栈结构 1.入栈 2.出栈 3.栈长度 4.栈顶元素 5.退出"""print infowhile 1: choice = raw_input("请输入你的选择:") if choice == "1": in_value = raw_input("入栈元素:") stack.append(in_value) print "元素%s入栈成功!" %(in_value) print stack elif choice == "2": if stack: out_value = stack.pop() print "元素%s出栈成功!" %(out_value) print stack else: print "栈为空!" elif choice == "3": print "栈长度为%d" %(len(stack)) elif choice == "4": if stack: print "栈顶元素为%s" %(stack[-1]) else: print "栈为空" elif choice == "5": exit(0) else: print "请输入正确选择!"
Test results:
2. Data structure of the list build queue:
Features of the queue: FIFO
#!/usr/bin/env python#coding:utf-8queue = []info = """ 队列结构 1.入队 2.出队 3.队长度 4.队头元素 5.队尾元素 6.退出"""print infowhile 1: choice = raw_input("请输入你的选择:") if choice == "1": in_value = raw_input("入队元素:") queue.append(in_value) print "元素%s入队成功!" % (in_value) print queue elif choice == "2": if queue: out_value = queue.pop(0) print "元素%s出队成功!" % (out_value) print queue else: print "队为空!" elif choice == "3": print "队长度为%d" % (len(queue)) elif choice == "4": if queue: print "队头元素为%s" % (queue[0]) else: print "队为空" elif choice == "5": if queue: print "队尾元素为%s" % (queue[-1]) else: print "队为空" elif choice == "6": exit(0) else: print "请输入正确选择!"
Test results:
The difference between the 3.Is and equals sign:
String-resident mechanism:
- For smaller strings, the ID is the same
- For longer strings, the IDs are not the same because a copy of the string does not reside.
Note: When testing, be sure to test in an interactive environment.
Test:In [1]: a = ‘hello‘
In [2]: b = ' Hello '
In [3]: Print ID (a), id (b)
40886560 40886560
In [4]: c = ' Hello Java world '
In [5]: D = ' Hello Java world '
In [6]: Print ID (c), id (d)
40923296 40923464
In [7]: print C is D
False
In [8]: E = ' python '
In [9]: F = "". Join ([' P ', ' y ', ' t ', ' h ', ' o ', ' n '])
In [ten]: Print ID (e), id (f)
140309747759888 40886608
结论:Is表示的是对象标识符;表示两个变量的值是否在统一块内存空间;== 表示的是值是否相等总结: is返回值为True, ==返回一定是True;深拷贝与浅拷贝: 1. 直接赋值, 只是把新的变量指向li的内存空间, 没有复制;当li改变, li1也随之改变;
In [all]: Li = [1, 2, 3]
In []: Li1 = li
in [+]: ID (LI)
OUT[13]: 40893688
in [+]: ID (LI1)
OUT[14]: 40893688
2. 浅拷贝: 拷贝出一份副本, 但是没有拷贝子对象(列表里面的列表对象);不完全拷贝- 切片li[:]
in [[]: Li1 = li[:]
in [+]: ID (LI), id (LI1)
OUT[16]: (40893688, 40891672)
- Copy.copy ()
in [+]: li = [' Fentiao ', ' Zhurou ', [' Fensi ', ' Fendai ']
In []: Li1 = li[:]
in [+]: ID (LI), id (LI1)
OUT[19]: (40891600, 40878592)
In []: ID (li[-1]), ID (li[-1])
OUT[20]: (40906264, 40906264)
in [+]: Import copy
In []: Li2 = Copy.copy (LI)
In []: ID (LI), id (LI1), ID (li2)
OUT[23]: (40891600, 40878592, 40865016)
In []: ID (li[-1]), ID (li1[-1]), ID (li2[-1])
OUT[24]: (40906264, 40906264, 40906264)
3.深拷贝: 里面的所有对象重新拷贝, 包括子对象;
in [+]: Li3 = Copy.deepcopy (LI)
In []: ID (li[-1]), ID (li1[-1]), ID (li3[-1])
OUT[26]: (40906264, 40906264, 40879960)
元组(tuple)1.元组创建可以把元组看作一个容器,任何数据类型都可以放在这个容器里面;通过赋值方式创建元组
in [+]: T = (1, 1.0, 2j, True, (+/-))
in [+]: print t
(1, 1.0, 2j, True, (1, 2, 3))
定义单个元组,一定要在这个元素后面加逗号
in []: T1 = (1,)
in [+]: Print type (t1)
<type ' tuple ' >
通过工厂方法创建元组
in [+]: t = tuple ()
in [+]: Print type (t)
<type ' tuple ' >
2.元组的操作索引切片连接重复成员操作符`In [33]: t = (1, 1.0, 1L, 1+2j, ‘hello‘, [1,2])`正向索引与反向索引以及元组嵌套时元素的访问
In []: Print t[0], t[-1], t[-1][-1]
1 [1, 2] 2
逆转元组元素
in [+]: print t[::-1]
([1, 2], ' Hello ', (1+2j), 1L, 1.0, 1)
连接
in [+]: Print t+ (+/-)
(1, 1.0, 1L, (1+2j), ' Hello ', [1, 2], 1, 2, 3)
重复
In [PNS]: print T * 3
(1, 1.0, 1L, (1+2j), ' Hello ', [1, 2], 1, 1.0, 1L, (1+2j), ' Hello ', [1, 2], 1, 1.0, 1L, (1+2j), ' Hello ', [1, 2])
成员操作符
in [+]: Print 1 in T, 1 not in t
True False
3.元组是可迭代数据类型
in [+]: Allow_ips = (' 172.25.254.1 ', ' 172.25.254.12 ', ' 172.25.254.13 ')
In [All]: for IP in allow_ips:
....: Print IP
....:
172.25.254.1
172.25.254.12
172.25.254.13
测试练习:端口扫描器雏形扫描172.25.254.0/24 这个网络所有主机的ftp, ssh, http, mariadb, samba(21, 22, 80, 3306,3020)
IPS = []
For I in range (1, 255):
ip = ' 172.25.254. ' +STR (i)
ips.append(‘172.25.254.‘ + str(i))
Ports = (21, 22, 80, 3306, 3020)
For IP in IPs:
For Port in ports:
print ' [+] scanning%s:%d '% (IP, port)
4.元组方法count 统计次数
In []: T.count (1)
OUT[43]: 3
In []: T.index (1)
OUT[44]: 0
元组变量交换python 中后面如果诗歌表达式 从右往左算x,y= (2,1) #先计算右边的表达式y,x,在内存中开辟内存空间,生成元组(y,x):x,y = y,x #将x,y = (2,1) print x,y元组是不可变数据类型字典1.字典创建字典的简单版定义1:
D = {
: The front is called the key, key
#:后面的称为值,value#键值对(key-value)‘name‘: ‘root‘,‘passwd‘:‘westos‘
}
Print d[' name ']
Print d[' passwd ']
字典的升级版定义:
info = {
' Root ': {
' Name ': ' Root ',
' passwd ': ' Westos ',
' Age ': 18,
' Eamil ': [' [email protected] ', ' [email protected] '
},
‘student‘: { ‘name‘: ‘student‘, ‘passwd‘: ‘westos‘, ‘age‘: 18, ‘eamil‘: [‘[email protected]‘, ‘[email protected]‘]},
}
Print info[' root '
通过工厂函数创建字典
D = dict ()
Print type (d)
D = dict (A=1, b=2, c=3)
Print d, type (d)
fromkeys方法创建字典d = {}.fromkeys([‘user1‘, ‘user2‘, ‘user3‘])print d![](http://i2.51cto.com/images/blog/201803/26/7c2ea2a8bd710344c1aacda79373e5eb.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)测试练习:批量生成卡号并初始化密码要求描述:1.生成银行卡号, 前5位为:61021 后面4位: 1~10002.并给每个银行卡初始化密码为6666663. 每5个为一行
Cardids = []
For I in range (1, 1001):
Cardid = "61021%.4d"% (i)
Cardids.append ((Cardid))
Cardinfo = {}.fromkeys (cardids, ' 666666 ')
#print Len (cardinfo)
For I, J in Enumerate (Cardinfo):
if i % 5 == 0: printprint j,
测试结果:![](http://i2.51cto.com/images/blog/201803/26/d1885af95cc9532d3db6b5e9933e242e.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)2.字典的特性不可行的特性: 索引, 切片, 连接, 重复, (因为dict是无序的数据类型;)可行的特性: 成员操作符3.字典操作字典值增加update(key=value, .....) - 如果key值存在, 更新该key对应的value值; - 如果key不存在, 添加key-value值;
In [1]: D = dict (A=1, b=2)
In [2]: D
Out[2]: {' A ': 1, ' B ': 2}
In [3]: D.update (c=5,d=6)
In [4]: D
Out[4]: {' A ': 1, ' B ': 2, ' C ': 5, ' d ': 6}
In [5]: D.update (a=10,d=100,f=9)
In [6]: D
Out[6]: {' A ': ten, ' B ': 2, ' C ': 5, ' d ': +, ' F ': 9}
setdefault(key,value) - 如果key值存在, 不操作; - 如果key不存在, 添加key-value值;
In [1]: D = dict (A=1, b= 2)
In [2]: D.setdefault (' A ', 10)
OUT[2]: 1
In [3]: D
Out[3]: {' A ': 1, ' B ': 2}
In [4]: D.setdefault (' F ', 10)
OUT[4]: 10
In [5]: D
Out[5]: {' A ': 1, ' B ': 2, ' F ': 10}
字典值查看
In [6]: D.keys () #查询key值
OUT[6]: [' A ', ' B ', ' F ']
In [7]: d.values () #查询values值
OUT[7]: [1, 2, 10]
In [8]: D.items () #查询键值对
OUT[8]: [(' A ', 1), (' B ', 2), (' F ', 10)]
In [9]: for I,j in D.items ():
...: Print i,j
...:
A 1
B 2
F 10
In []: D.has_key (' a ') #查询字典里是否含有 ' a ' this key value
OUT[10]: True
字典删除 pop(k[,d]):- 如果key存在, 删除key-value;- 如果key不存在,判断d是否存在: - 如果d不存在, 报错KeyError; - 如果d存在, 返回d;
In [all]: D
OUT[11]: {' A ': 1, ' B ': 2, ' F ': 10}
In []: D.pop (' e ', 1)
OUT[12]: 1
In []: D.pop (' a ')
OUT[13]: 1
in [+]: D
OUT[14]: {' B ': 2, ' F ': 10}
In []: D.pop (' B ', 10)
OUT[15]: 2
popitem():随机删除key-value对;当字典为空时报错;
in [+]: D
OUT[19]: {' A ': 1, ' B ': 2, ' C ': 3, ' F ': 10}
In []: D.popitem ()
OUT[20]: (' A ', 1)
in [+]: D
OUT[21]: {' B ': 2, ' C ': 3, ' F ': 10}
in [[]: Del d[' C ']
In [all]: D
OUT[23]: {' B ': 2, ' F ': 10}
in [[]: Del d[' C ']
Keyerror Traceback (most recent)
<ipython-input-24-975cd7d7076f> in <module> ()
----> 1 del d[' C ')
Keyerror: ' C '
In [the]: D.clear () #删除字典里所有元素
in [+]: D
OUT[35]: {}
In [approx]: del d #删除整个字典
利用if语句实现switch(实现四则运算)
#!/usr/bin/env python
#coding: Utf-8
From the future import division
While 1:
NUM1 = input (' NUM1: ')
Oper = raw_input (' operator: ')
num2 = input (' Num2: ')
if oper == "+": print num1 +num2elif oper == ‘-‘: print num1 - num2elif oper == ‘/‘: print num1 / num2elif oper == ‘*‘: print num1 * num2else: print ‘error‘
测试结果:![](http://i2.51cto.com/images/blog/201803/26/11853b8377d329c7a2fd22a3f3851569.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)利用字典与函数实现switch(实现四则运算)
#!/usr/bin/env python
#coding: Utf-8
From the future import division
NUM1 = input (' NUM1: ')
Oper = raw_input (' operator: ')
num2 = input (' Num2: ')
def add (NUM1, num2):
return NUM1 + num2
def div (NUM1, num2):
If num2 = = 0:
Raise IOError
Else
Return num1/num2
D = {
' + ': Add,
'-': num1-num2,
": Num1 num2,
'/': Div,
}
If Oper in D:
Print D[oper] (NUM1, num2)
Else
print ' ERROR '
测试结果:![](http://i2.51cto.com/images/blog/201803/26/6492a6613209fd1870562b76426ebc3d.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)字典遍历
#!/usr/bin/env python
#coding: Utf-8
Favourite_places = {
' Lee ': [' Xian ', ' Hangzhou '],
' Fentiao ': [' Hanzhong ', ' Xianyang ']
}
For name in Favourite_places:
print "\ n" + name.title () + "' s favourite place is:"
For place in Favourite_places[name]:
Print Place
Test Result:! [] (http://i2.51cto.com/images/blog/201803/26/a7e27f86f13291ea930275d8a4ef16b6.png?x-oss-process=image/ watermark,size_16,text_qduxq1rp5y2a5a6i,color_ffffff,t_100,g_se,x_10,y_10,shadow_90,type_zmfuz3pozw5nagvpdgk=) Collection: The collection is a data type that is not duplicated; The key value in the dictionary cannot be duplicated; in [PNS]: s = {1, 2, 3, 4, 1, 2}in [MAX]: sout[38]: {1, 2, 3, 4} list Deduplication method One: can be converted to collection in [max]: Li = [1, 2, 3, 4, 1, 2, 4]in [max]: List (set (LI)) out[40]: [1, 2, 3, 4] method two: Convert to a dictionary, take out all keys; Note: Dict () cannot convert the list directly into a dictionary; in [+]: {}.fromke Ys (LI). Keys () out[41]: [1, 2, 3, 4] Define a collection to define an empty collection in [the]: S1 = set () in []: Type (S1) out[45]: Set dictionary can be converted to set in []: D = dict (a= 1, b=2, c=3) in []: set (d) out[47]: {' A ', ' B ', ' C '} set is an unordered data type; in []: s = {2, 3, N, 89}in []: S.add (+) in [[]: P Rint Sset ([2, 3, 12, 13, 89, 91]) collection unsupported attributes: Index, slice, duplicate, connection set supported attributes: The member operator collection is an iterative object, so the for loop traversal element is supported; in [Wuyi]: s = {91, 2, 3, 12, 89}in [*]: For i in S: ....: Print I ...: 91,892,312 add and delete check increase in [+]: s = {1, 2, 3}in [si]: S.add (4) in [55]: S.update ({3,4,5,6}) in [the]: s.update (' hello ') in [57]: S.update ([1,2,37,10]) in []: sout[58]: {1, 2, 3, 4, 5, 6,, Notoginseng, ' e ', ' h ', ' l ', ' o '} delete in []: S1.pop () out[68]: 1In [s1out[69]: {3, 4, 5}in []: S1.remove (5) in []: s1out[75]: {4}in [+]: S1.discard (4) in []: s1out[79]: Set (), Replenishment set in [3]: S1 = {1, 2, 3, 4}in [4]: S2 = {1, 2, 4, 5} #交集In [5]: S1 & S2out[5]: {1, 2, 4} #补集In [6]: S1 | S2out[6]: {1, 2, 3, 4, 5} #差集In [7]: S1-s2out[7]: {3}
Python tuple Dictionary collection