hongmeigui22027 发表于 2018-8-5 08:41:31

python元组 字典 集合

  1.列表构建栈的数据结构:
  栈的特点:先进后出
  

#!/usr/bin/env python  
#coding:utf-8
  
stack = []
  

  
info = """
  

  栈结构
  1.入栈
  2.出栈
  3.栈长度
  4.栈顶元素
  5.退出
  

  
"""
  
print info
  

  
while 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 "请输入正确选择!"
  

  测试结果:

  2.列表构建队列的数据结构:
  队列的特点:先进先出
  

#!/usr/bin/env python  
#coding:utf-8
  
queue = []
  

  
info = """
  

  队列结构
  1.入队
  2.出队
  3.队长度
  4.队头元素
  5.队尾元素
  6.退出
  

  
"""
  
print info
  

  
while 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)
  else:
  print "队为空"
  elif choice == "5":
  if queue:
  print "队尾元素为%s" % (queue[-1])
  else:
  print "队为空"
  elif choice == "6":
  exit(0)
  else:
  print "请输入正确选择!"
  

  测试结果:

  3.Is和等于号的区别:
  字符串驻留机制:


[*]对于较小的字符串,id相同
[*]对于较长的字符串,id不相同,因为不会驻留字符串的副本。  注意:在进行测试时,一定要在交互式环境测试。
  测试:
  

  
In : a = 'hello'

  In : b = 'hello'

  In : print>  40886560 40886560
  In : c = 'hello java world'
  In : d = 'hello java world'

  In : print>  40923296 40923464
  In : print c is d
  False
  In : e = 'python'
  In : f = "".join(['p', 'y', 't', 'h', 'o', 'n'])

  In : print>  140309747759888 40886608
  

  
结论:
  
Is表示的是对象标识符;表示两个变量的值是否在统一块内存空间;
  
== 表示的是值是否相等
  

  
总结: is返回值为True, ==返回一定是True;
  
深拷贝与浅拷贝:
  1. 直接赋值, 只是把新的变量指向li的内存空间, 没有复制;当li改变, li1也随之改变;
  

  In : li =
  In : li1 = li

  In :>  Out: 40893688

  In :>  Out: 40893688
  

  
2. 浅拷贝: 拷贝出一份副本, 但是没有拷贝子对象(列表里面的列表对象);不完全拷贝
  
- 切片li[:]
  

  In :li1 = li[:]

  In :>  Out: (40893688, 40891672)


[*]copy.copy()  In :li = ['fentiao', 'zhurou', ['fensi', 'fendai']]

  In : li1 = li[:]

  In :>  Out: (40891600, 40878592)

  In :>  Out: (40906264, 40906264)
  In : import copy
  In : li2 = copy.copy(li)

  In :>  Out: (40891600, 40878592, 40865016)

  In : >  Out: (40906264, 40906264, 40906264)
  

3.深拷贝: 里面的所有对象重新拷贝, 包括子对象;  

  In : li3 = copy.deepcopy(li)

  In :>  Out: (40906264, 40906264, 40879960)
  

元组(tuple)  
1.元组创建
  
可以把元组看作一个容器,任何数据类型都可以放在这个容器里面;
  
通过赋值方式创建元组
  

  In : t = (1, 1.0, 2j, True, (1,2,3))
  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 : t = (1, 1.0, 1L, 1+2j, 'hello', )`
  
正向索引与反向索引以及元组嵌套时元素的访问
  

  In : print t, t[-1], t[-1][-1]
  1 2
  

逆转元组元素  

  In :print t[::-1]
  (, 'hello', (1+2j), 1L, 1.0, 1)
  

连接  

  In :print t+(1,2,3)
  (1, 1.0, 1L, (1+2j), 'hello', , 1, 2, 3)
  

  
重复
  

  In : print t * 3
  (1, 1.0, 1L, (1+2j), 'hello', , 1, 1.0, 1L, (1+2j), 'hello', , 1, 1.0, 1L, (1+2j), 'hello', )
  

成员操作符  

  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 : 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: 3
  

index 显示索引   

  In : t.index(1)
  Out: 0
  

元组变量交换  
python 中后面如果诗歌表达式从右往左算
  
x,y= (2,1) #先计算右边的表达式y,x,在内存中开辟内存空间,生成元组(y,x):
  
x,y = y,x#将x,y = (2,1)
  
print x,y
  
元组是不可变数据类型
  

  
字典
  
1.字典创建
  
字典的简单版定义1:
  

  d = {

:前面的称为键,key
  

#:后面的称为值,value  
#键值对(key-value)
  
'name': 'root',
  
'passwd':'westos'
  

  }
  print d['name']
  print d['passwd']
  

  
字典的升级版定义:
  

  info = {
  'root':{
  'name': 'root',
  'passwd':'westos',
  'age':18,
  'eamil':['westos@qq.com', 'redhat@qq.com']
  },
  

'student': {  'name': 'student',
  'passwd': 'westos',
  'age': 18,
  'eamil': ['westos@qq.com', 'redhat@qq.com']
  
},
  

  }
  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~1000
  
2.并给每个银行卡初始化密码为666666
  
3. 每5个为一行
  

  

  cardids = []
  for i in range(1, 1001):
  cardid = &quot;61021%.4d&quot; % (i)
  cardids.append((cardid))
  cardInfo = {}.fromkeys(cardids, '666666')
  #print len(cardInfo)
  for i, j in enumerate(cardInfo):
  

if i % 5 == 0:  print
  
printj,
  

测试结果:  
![](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 : d = dict(a=1, b=2)
  In : d
  Out: {'a': 1, 'b': 2}
  In : d.update(c=5,d=6)
  In : d
  Out: {'a': 1, 'b': 2, 'c': 5, 'd': 6}
  In : d.update(a=10,d=100,f=9)
  In : d
  Out: {'a': 10, 'b': 2, 'c': 5, 'd': 100, 'f': 9}
  

setdefault(key,value)  - 如果key值存在, 不操作;
  - 如果key不存在, 添加key-value值;
  

  In : d = dict(a=1, b= 2)
  In : d.setdefault('a', 10)
  Out: 1
  In : d
  Out: {'a': 1, 'b': 2}
  In : d.setdefault('f', 10)
  Out: 10
  In : d
  Out: {'a': 1, 'b': 2, 'f': 10}
  

  
字典值查看
  

  In : d.keys()   #查询key值
  Out: ['a', 'b', 'f']
  In : d.values()   #查询values值
  Out:
  In : d.items()   #查询键值对
  Out: [('a', 1), ('b', 2), ('f', 10)]
  In :for i,j in d.items():
  ...:   print i,j
  ...:
  a 1
  b 2
  f 10
  In : d.has_key('a') #查询字典里是否含有‘a’这个key值
  Out: True
  

字典删除  pop(k[,d]):
  
- 如果key存在, 删除key-value;
  
- 如果key不存在,判断d是否存在:
  - 如果d不存在, 报错KeyError;
  - 如果d存在, 返回d;
  

  

  In : d
  Out: {'a': 1, 'b': 2, 'f': 10}
  In : d.pop('e', 1)
  Out: 1
  In : d.pop('a')
  Out: 1
  In : d
  Out: {'b': 2, 'f': 10}
  In : d.pop('b', 10)
  Out: 2
  

popitem():随机删除key-value对;当字典为空时报错;  

  In : d
  Out: {'a': 1, 'b': 2, 'c': 3, 'f': 10}
  In : d.popitem()
  Out: ('a', 1)
  In : d
  Out: {'b': 2, 'c': 3, 'f': 10}
  In : del d['c']
  In : d
  Out:{'b': 2, 'f': 10}

In:del d['c']
  KeyError                                  Traceback (most recent call last)
  <ipython-input-24-975cd7d7076f> in <module>()
  ----> 1 del d['c']
  KeyError: 'c'
  In : d.clear()   #删除字典里所有元素
  In : d
  Out: {}
  In : del d      #删除整个字典
  

  
利用if语句实现switch(实现四则运算)
  

  #!/usr/bin/env python
  #coding:utf-8
  from future import division
  while 1:
  num1 = input('Num1:')
  oper = raw_input('操作符:')
  num2 = input('Num2:')
  

if oper == "+":  printnum1 +num2
  
elif oper == '-':
  printnum1 - num2
  
elif oper == '/':
  printnum1 / num2
  
elif oper == '*':
  printnum1 * num2
  
else:
  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 future import division
  num1 = input('Num1:')
  oper = raw_input('操作符:')
  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(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 &quot;\n&quot; + name.title() + &quot;'s favourite place are:&quot;
  for place in favourite_places:
  print place
  

  
测试结果:
  
![](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=)
  

  
集合:
  
集合是不重复的数据类型;字典中的key值不能重复;
  
In : s = {1, 2, 3, 4, 1, 2}
  

  
In : s
  
Out: {1, 2, 3, 4}
  

  
列表去重
  
方法一:可以转换为集合
  

  
In : li =
  

  
In : list(set(li))
  
Out:
  
方法二:转化为字典,拿出所有的key; 注意: dict()不能直接将列表转化为字典;
  
In : {}.fromkeys(li).keys()
  
Out:
  
定义集合
  
定义一个空集合
  
In : s1 = set()
  

  
In : type(s1)
  
Out: set
  
字典可以转化为集合
  
In : d = dict(a=1, b=2, c=3)
  

  
In : set(d)
  
Out: {'a', 'b', 'c'}
  集合是无序的数据类型;
  
In : s = {91, 2, 3, 12, 89}
  

  
In : s.add(13)
  

  
In : print s
  
set()
  
集合不支持的特性: 索引, 切片, 重复,连接
  
集合支持的特性: 成员操作符
  
集合是可迭代的对象, 因此支持for循环遍历元素;
  
In : s = {91, 2, 3, 12, 89}
  

  
In : for i in s:
  ....:   print i
  ....:
  
91
  
89
  
2
  
3
  
12
  
集合的增删查改
  
增加
  
In : s = {1, 2, 3}
  

  
In : s.add(4)
  

  
In : s.update({3,4,5,6})
  

  
In : s.update('hello')
  

  
In : s.update()
  

  
In : s
  
Out: {1, 2, 3, 4, 5, 6, 10, 37, 'e', 'h', 'l', 'o'}
  
删除
  
In : s1.pop()
  
Out: 1
  

  
In : s1
  
Out: {3, 4, 5}
  
In : s1.remove(5)
  

  
In : s1
  
Out: {4}
  
In : s1.discard(4)
  

  
In : s1
  
Out: set()
  

  
集合的交,补差集
  
In : s1 = {1, 2, 3, 4}
  

  
In : s2 = {1, 2, 4, 5}
  
#交集
  
In : s1 & s2
  
Out: {1, 2, 4}
  
#补集
  
In : s1 |s2
  
Out: {1, 2, 3, 4, 5}
  
#差集
  
In : s1 -s2
  
Out: {3}
页: [1]
查看完整版本: python元组 字典 集合