python学习day3-栈队列元组

栈和队列
1.栈:先进后出  

stack = []

info = """
        栈操作
    1.入栈
    2.出栈
    3.栈长度
    4.栈顶元素
    5.退出
"""
while True:
    a = raw_input("请输入你的选项:")
    if a == '1':
        in_value = raw_input("入栈元素:")
        stack.append(in_value)
        print "元素%s入栈成功!"%(in_value)
        print stack
    elif a == '2':
        if stack:
            out_value = stack.pop()
            print "出栈成功"
            print stack
        else:
            print "栈为空!"
    elif a == '3':
        print "栈长度为%d"%(len(stack))
        print stack
    elif a == '4':
        if stack:
            print "栈顶元素为:%s" %(stack[-1])
        else:
            print "栈为空!"
    elif a == '5':
        exit(0)
    else:
        print "请输入正确的选项!"

2.队列:先进先出

queue = []

info = """
        队列操作
    1.入队列
    2.出队列
    3.队列长度
    4.队头元素
    5.退出
"""
while True:
    a = raw_input("请输入你的选项:")
    if a == '1':
        in_value = raw_input("入队列元素:")
        queue.append(in_value)
        print "元素%s入队列成功!"%(in_value)
        print queue
    elif a == '2':
        if queue:
            out_value = queue.pop(0)
            print "出队列成功"
            print queue
        else:
            print "队列为空!"
    elif a == '3':
        print "队列长度为%d"%(len(queue))
        print queue
    elif a == '4':
        if queue:
            print "队列顶元素为:%s" %(queue[0])
        else:
            print "队列为空!"
    elif a == '5':
        exit(0)
    else:
        print "请输入正确的选项!"

3.is和等号的区别
一定要在交互式环境下测试
字符串驻留机制
- 对于较小的字符串,id相同
- 对于较长的字符串,id不相同,因为不会驻留字符串的副本
a = ‘hello’
b = ‘hello’
print id(a),id(b) true##一样
c = ‘hello python’
d = ‘hello python’
print id(c),id(d) false##不一样
e = ‘python’
f = “”.join([‘p’,’y’,’t’,’h’,’o’,’n’])
print id(e),id(f) false##不一样
结论:
is表示的是对象标识符,表示两个变量的值是否在同一块内存空间
**==表示的是值是否相等
4.拷贝

(1)li1 = li
直接赋值,会指向原来的内存空间,不会改变id
(2)浅拷贝:拷贝出一份副本,但是没有拷贝出字对象,所以是不完全拷贝
方法一:

li1 = li[:]

列表id不一样,但元素id一样

方法二:

import copy
li2 = copy.copy(li)

同方法一效果一样

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

deepcopy:深拷贝
li3 = copy.deepcopy(li)

列表及元素id都不一样
5.元组
 1.元组的定义

t = (1,2,3,4)

当只有一个元素是必须家逗号

t = (1,)

定义空元组

扫描二维码关注公众号,回复: 3444514 查看本文章
t = tuple()     ##定义空列表:li = list()

2.元组的特性
索引

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

切片

print t[::-1]

连接

print t+(1,2,3)

重复

print t * 3

成员操作符

print 1 in t
print 1 not in t

3.元组可迭代

t = (1,1.0,1L,1+2j,'hello',[1,2])
for i in t:
    print i

4.端口扫描器雏形

ips=[]
for i in range(1,255)
ips.append('172.25.254.'+str(i))
ports = (21,22,80,3306,8000)
for ip in ips:
    for port in ports:
        print '[+] Scanning %s:%d'%(ip,port)

5.元组使用

t.count(value)      ##该字符出现的次数
t.index(value)      ##返回value在元组中的偏移量(即索引值)
x=2 
y=1
(1)先计算右边的表达式y,x,在内存中开辟内存空间,生成元组
(2)将x,y = (2, 1)
x,y = y,x
print x,y
**测试两种数据值交换的时间对比
from timeit import Timer
print Timer('temp = x;x = y;y = temp','x = 2;y = 1').timeit()
print Timer('x,y = y,x','x = 2;y = 1').timeit()

5.字典创建

hash哈希 =======字典dict

类型是dict

d = {
    #前面的称为键,key
    #后面的称为值,value
    #键值对(key-value)
    'name':'root',
    'passwd':'westos'
}
print d['name']
print d['passwd']

创建字典的三种方式

info = {
    'root':{
        'name':'root',
        'passwd':'westos',
        'age':18,
        'email':['[email protected]','[email protected]']
    },
    'student':{
        'name':'student',
        'passwd':'redhat',
        'age':22,
        'email':['[email protected]','[email protected]']
    },
}
print info['student']

通过工厂函数创建字典

d = dict(a=1,b=2,c=3)
print d,type(d)
dict = {}
print type(dict)

fromkeys方法创建字典

d={}.fromkeys(['user1','user2','user3'],'westos')
print d

题目:用字典生成银行卡号

cardisd = []
for i in range(1,1001):
    cardid = "610121%.4d"%(i)
    cardids.append(cardid)
cardinfo = {}.fromkeys(cardids,"westos")
print len(cardinfo)

内置方法:min,max,zip,enumerate
字典中默认遍历字典的key值

提升:每行显示5个
for i,j in enumerate(cardinfo):
    if i%5 == 0:
        print
    print  print i,j,a[j],

7.字典特性
不可行:索引,切片,连接,重复(因为字典是无序的数据类型)
可行的特性:成员操作符;

'a' in d  返回一个布尔值

8.字典的增加

1.update(key=value,....)

在增加的时候如果key存在,更新对应的value值

d.update(a=10,b=2,c=3)
2.setdefault(key,value)

如果存在不操作,如果不存在添加key-value值 

9.字典的查看

d.items()
for i,j in d.items():
    print i,j

10.字典的删除

(1)d.pop(k[,d]):
如果key存在删除对应的key-value;
如果key不存在,判断d是否存在:
如果d不存在就报错KeyError
如果d存在,就删除d对应的值
(2)d.popitem
随机删除
(3)d.clear
清空
(4)del d
从内存中全部删除




 

猜你喜欢

转载自blog.csdn.net/qq_41636653/article/details/82627223
今日推荐