python空字典和空集合_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[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)

通过工厂方法创建元组

In [31]: t = tuple()

In [32]: print type(t)

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

![](https://s4.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 = "61021%.4d" % (i)

cardids.append((cardid))

cardInfo = {}.fromkeys(cardids, '666666')

#print len(cardInfo)

for i, j in enumerate(cardInfo):

if i % 5 == 0:

print

print j,

测试结果:

![](https://s4.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)

in ()

----> 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 +num2

elif oper == '-':

print num1 - num2

elif oper == '/':

print num1 / num2

elif oper == '*':

print num1 * num2

else:

print 'error'

测试结果:

![](https://s4.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'

测试结果:

![](https://s4.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

测试结果:

![](https://s4.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]: s

Out[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 s

set([2, 3, 12, 13, 89, 91])

集合不支持的特性: 索引, 切片, 重复,连接

集合支持的特性: 成员操作符

集合是可迭代的对象, 因此支持for循环遍历元素;

In [51]: s = {91, 2, 3, 12, 89}

In [52]: for i in s:

....: print i

....:

91

89

2

3

12

集合的增删查改

增加

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]: s

Out[58]: {1, 2, 3, 4, 5, 6, 10, 37, 'e', 'h', 'l', 'o'}

删除

In [68]: s1.pop()

Out[68]: 1

In [69]: s1

Out[69]: {3, 4, 5}

In [74]: s1.remove(5)

In [75]: s1

Out[75]: {4}

In [78]: s1.discard(4)

In [79]: s1

Out[79]: set()

集合的交,补差集

In [3]: s1 = {1, 2, 3, 4}

In [4]: s2 = {1, 2, 4, 5}

#交集

In [5]: s1 & s2

Out[5]: {1, 2, 4}

#补集

In [6]: s1 | s2

Out[6]: {1, 2, 3, 4, 5}

#差集

In [7]: s1 - s2

Out[7]: {3}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值