Python语言元组 字典 集合
小标 2019-01-02 来源 : 阅读 451 评论 0

摘要:本文主要向大家介绍了Python语言元组 字典 集合,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。

本文主要向大家介绍了Python语言元组 字典 集合,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。

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

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

测试结果:

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

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


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

对于较小的字符串,id相同

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

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 [10]: print id(e), id(f)
140309747759888 40886608

结论:Is表示的是对象标识符;表示两个变量的值是否在统一块内存空间;== 表示的是值是否相等总结: is返回值为True, ==返回一定是True;深拷贝与浅拷贝: 1. 直接赋值, 只是把新的变量指向li的内存空间, 没有复制;当li改变, li1也随之改变;

In [11]: li = [1, 2, 3]

In [12]: li1 = li

In [13]: id(li)
Out[13]: 40893688

In [14]: id(li1)
Out[14]: 40893688

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

In [15]:  li1 = li[:]

In [16]: id(li), id(li1)
Out[16]: (40893688, 40891672)

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

In [18]: li1 = li[:]

In [19]: id(li), id(li1)
Out[19]: (40891600, 40878592)

In [20]: id(li[-1]), id(li[-1])
Out[20]: (40906264, 40906264)

In [21]: import copy

In [22]: li2 = copy.copy(li)

In [23]: id(li), id(li1), id(li2)
Out[23]: (40891600, 40878592, 40865016)

In [24]:  id(li[-1]), id(li1[-1]), id(li2[-1])
Out[24]: (40906264, 40906264, 40906264)

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

In [25]: li3 = copy.deepcopy(li)

In [26]: id(li[-1]), id(li1[-1]), id(li3[-1])
Out[26]: (40906264, 40906264, 40879960)

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

In [27]: t = (1, 1.0, 2j, True, (1,2,3))
In [28]: print t
(1, 1.0, 2j, True, (1, 2, 3))

 定义单个元组,一定要在这个元素后面加逗号

In [29]: t1 = (1,)
In [30]: print type(t1)
<type 'tuple'>

通过工厂方法创建元组

In [31]: t = tuple()

In [32]: print type(t)
<type 'tuple'>

2.元组的操作索引切片连接重复成员操作符`In [33]: t = (1, 1.0, 1L, 1+2j, 'hello', [1,2])`正向索引与反向索引以及元组嵌套时元素的访问

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

逆转元组元素

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

连接

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

重复

In [37]: 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 [38]: print 1 in t, 1 not in t
True False

3.元组是可迭代数据类型

In [41]: allow_ips = ('172.25.254.1', '172.25.254.12', '172.25.254.13')
In [42]: 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 [43]: t.count(1)      
Out[43]: 3

index 显示索引

In [44]: 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 = {

:前面的称为键,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![](//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,
测试结果:![](//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': 10, 'b': 2, 'c': 5, 'd': 100, '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 [10]: d.has_key('a') #查询字典里是否含有‘a’这个key值
Out[10]: True

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

In [11]: d
Out[11]: {'a': 1, 'b': 2, 'f': 10}

In [12]: d.pop('e', 1)
Out[12]: 1

In [13]: d.pop('a')
Out[13]: 1

In [14]: d
Out[14]: {'b': 2, 'f': 10}

In [15]: d.pop('b', 10)
Out[15]: 2

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

In [19]: d
Out[19]: {'a': 1, 'b': 2, 'c': 3, 'f': 10}

In [20]: d.popitem()
Out[20]: ('a', 1)

In [21]: d
Out[21]: {'b': 2, 'c': 3, 'f': 10}

In [22]: del d['c']

In [23]: d
Out[23]: {'b': 2, 'f': 10}

In [24]: del d['c']

KeyError                                  Traceback (most recent call last)
<ipython-input-24-975cd7d7076f> in <module>()
----> 1 del d['c']

KeyError: 'c'
In [34]: d.clear()     #删除字典里所有元素

In [35]: d
Out[35]: {}

In [36]: 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 == "+":    print  num1 +num2elif oper == '-':    print  num1 - num2elif oper == '/':    print  num1 / num2elif oper == '*':    print  num1 * num2else:    print 'error'
测试结果:![](//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[oper](num1, num2)
else:
print 'error'

测试结果:![](//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 are:"
for place in favourite_places[name]:
print place

测试结果:![](//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 [37]: s = {1, 2, 3, 4, 1, 2}In [38]: sOut[38]: {1, 2, 3, 4}列表去重方法一:可以转换为集合In [39]: li = [1, 2, 3, 4, 1, 2, 4]In [40]: list(set(li))Out[40]: [1, 2, 3, 4]方法二:转化为字典,拿出所有的key; 注意: dict()不能直接将列表转化为字典;In [41]: {}.fromkeys(li).keys()Out[41]: [1, 2, 3, 4]定义集合定义一个空集合In [44]: s1 = set()In [45]: type(s1)Out[45]: set字典可以转化为集合In [46]: d = dict(a=1, b=2, c=3)In [47]: set(d)Out[47]: {'a', 'b', 'c'} 集合是无序的数据类型;In [48]: s = {91, 2, 3, 12, 89}In [49]: s.add(13)In [50]: print sset([2, 3, 12, 13, 89, 91])集合不支持的特性: 索引, 切片, 重复,连接集合支持的特性: 成员操作符集合是可迭代的对象, 因此支持for循环遍历元素;In [51]: s = {91, 2, 3, 12, 89}In [52]: for i in s:   ....:     print i   ....:     91892312集合的增删查改增加In [53]: s = {1, 2, 3}In [54]: s.add(4)In [55]: s.update({3,4,5,6})In [56]: s.update('hello')In [57]: s.update([1,2,37,10])In [58]: sOut[58]: {1, 2, 3, 4, 5, 6, 10, 37, 'e', 'h', 'l', 'o'}删除In [68]: s1.pop()Out[68]: 1In [69]: s1Out[69]: {3, 4, 5}In [74]: s1.remove(5)In [75]: s1Out[75]: {4}In [78]: s1.discard(4)In [79]: s1Out[79]: 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有所帮助,更多内容请关注职坐标编程语言Python频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程