python基础篇 day2


1.list 列表
#增加  append  insert
name = ['0alex','1jack','2snow','3pig']

print(name)
name.append('4snake') #追加到末尾
print(name)

name.insert(1,'xxxx') #插入到下标为1的位置
name.insert(3,'qqqq')
print(name)

  

#更改下标对应元素
#打印下标对应元素
#循环打印list元素
name1 = ['0alex','1jack','2snow','3pig']
name1[2] = 'update'
print(name1)
print(name1[0])
print(name1[3])
print(name1[-1])  #倒数第一个 打印
print(name1[-2])    #倒数第2个 打印


for i in name1:  #循环打印list元素
    print(i)

  

#正向切片
name2 = ['0alex','1jack','2snow','3pig','4dog']
print(name2)
print(name2[0:3])  #切片[0,3)
print(name2[:3])  #切片[0,3)

print(name2[0:-1])  #切片[0,-1) 除了倒数第一个都打印


#反向切片
name3 = ['0alex','1jack','2snow','3pig','4dog']
print(name3)
print(name3[-1:-3])  #打印为空[]  -1是最后一个
print(name3[-3:-1])   #[-3,-1)


#步长切片
print(name2[0:-1:2])
#['0alex', '1jack', '2snow', '3pig']
#['0alex', '2snow']

  

#索引(获取下标)  和统计

name4 = ['0alex','1jack','2snow','3pig','4dog','4dog']
print(name4)
print(name4.index('1jack'))  #获取元素对应的下标
print(name4[name4.index('1jack')])  #获取元素对应的下标,下标对应的元素
print(name4.count('4dog'))  #统计几个4dog

  

#删除
name4.remove('4dog') #删除
print(name4)
del name4[1]  #删除下标1的
print(name4)
name4.pop(2) #删除下标2的
name4.pop()  #删除,默认下标-1的
print(name4)

  

#翻转 排序
name5 = ['0alex','1jack','2snow','3pig','4dog']
name5.reverse() #翻转
print(name5)

name5.sort()  #排序
print(name5)

  

#扩展

age  = ['22','33','44']
job = ['it','teacher','student']

age.extend(job)  #['22', '33', '44', 'it', 'teacher', 'student']

print(age)
print(job)

  

2. 深copy 浅copy

#浅copy
name = ['0alex','1jack',['21root','22redhat'],'3snake']
print('name>',name)
name2 = name.copy()

name[3] = '吖吖'
print('name>',name)
print('name2>',name2)

name[2][0] = '答复'
print('name>',name)
print('name2>',name2)

  

#浅copy 和浅copy的区别
import copy
name3 = ['0alex','1jack',['21root','22redhat'],'3snake']

name4 = copy.copy(name3)    #name4只是复制了name3,name3改变,它也改变
name5  = copy.deepcopy(name3)  #name5 重新开辟一块内存地址,指针,name3改变,name5不改变

name3[2][0] = '答复'

print('name4>',name4)
print('name5>',name5)

  

#3种浅copy
import copy
person = ['0jack',['10alex','11root']]
person2 = copy.copy(person)

person3 = person[:]

person4 = list(person)

print(person2,person3,person4)

 

2. 元组

#元组, 不可以修改

'''
name = ('jack','alex')
name.append('root')
AttributeError: 'tuple' object has no attribute 'append'
'''

name = ('jack','alex')
print(name.count('alex'))
print(name.index('jack'))

  

 

#联合账户,共同存款
salary = 1000
count = ['name',['saving',salary]]
print(count)

alex = count[:]
wife = count[:]
alex[0]='alex'
wife[0]='wife'

count[1][1]= salary+1000
print(alex)
print(wife)

 

3.购物车程序

'''
程序练习 
请闭眼写出以下程序。
程序:购物车程序
需求:
1. 启动程序后,让用户输入工资,然后打印商品列表
2. 允许用户根据商品编号购买商品
3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
4. 可随时退出,退出时,打印已购买商品和余额
'''

 1 info = '''
 2 ----------------
 3 
 4 Welcome to CBBC
 5 
 6 ----------------
 7 '''
 8 print(info)
 9 
10 
11 salary = int(input('your salary > ').strip())
12 shopping_list = []
13 while True:
14     goods_list = [['air','10000'],['apple','8888'],['mi','3999'],['coffee','23'],['page','1']]
15     print(len(goods_list))
16     for index,item in enumerate(goods_list):
17         print(index,item )
18 
19 
20     choice = input('your choice [q:exit]> ').strip()
21     if choice.isnumeric()  and  0 <  int(choice) < len(goods_list):
22         choice = int(choice)
23 
24 
25         if int(goods_list[choice][1]) < salary :
26             salary -= int(goods_list[choice][1])
27             shopping_list.append(goods_list[choice][0])
28             print(salary)
29             print(shopping_list)
30         else:
31             print('余额不足')
32 
33     elif choice == 'q':
34         break
35     else:
36         print('请重新输入')
37 
38 
39 info_bye = '''
40 ---------------
41     bye - bye
42 ---------------
43 your salary:%s
44 your goods:%s
45 '''%(salary,shopping_list)
46 
47 print(info_bye)
View Code

 

 

#打印list的#下标,索引 #下标和索引
goods_list = [['air','10000'],['apple','8888'],['mi','3999'],['coffee','23'],['page','1']]

#下标,索引
for index,item in enumerate(goods_list):
    print(index,item)

#索引
for i in goods_list:
    print(i)

#下标
for i in goods_list:
    print(goods_list.index(i))

 

#判断是不是数字???
choice = input('>')
if choice.isdigit():
    print('ok')
elif choice.isnumeric():
    print('11')

  

#高亮显示
print('this is a  book')
print('this is a \033[32;1m book \033[0m')

  

4.字符串str

name = 'my name is \t alex'

print(name.capitalize())  #My name is 	 alex

print(name.count('a')) #2

print(name.center(50,'+')) #++++++++++++++++my name is 	 alex+++++++++++++++++

print(name.endswith('ex'))  #以ex结尾i 返回True

print(name.expandtabs(30))  #\t 转换成空格

print(name.find('name')) #3

print(name[name.find('name'):9])  #切片  name[3:9)

  

#拼接
name2  = 'my name is {name},age is {age}'
print(name2.format(name='alex',age='22'))
print(name2.format_map({'name':'jack','age':33}))

  

#判断是否是什么
print(name.isalnum())  #阿拉伯数字
print('123aa'.isalnum())
print('adfaDFAS'.isalpha())
print('233'.isdecimal())
print('-44'.isdigit()) #是否整数
print(' 9 44'.isnumeric()) #是否只有数字

print('asf##'.isdecimal())
print('My'.istitle())
print('My'.isprintable())
print('My'.isupper())

  

#拼接
print('My name is '.join('==/+'))

#  =   =   /   +

print('+'.join(['1','3','4']))
#1+3+4

print('aaaa'.ljust(50,'+'))
print('aaaa'.rjust(50,'+'))
print('aleEXSSnn'.zfill(20))
#00000000000aleEXSSnn

  

#大小写
print('SNAEKwe'.lower()) #snaekwe
print('SNAEKwe'.upper()) #SNAEKWE
print('aleEXSSnn'.swapcase())
#ALEexssNN

  

#去除空格,换行
print('\talex\t'.lstrip())
print('\talex\t'.rstrip())

#alex
# 	alex

print('       \nalex\t'.strip())
#alex

  

#替换
password = str.maketrans('abcde123','12345kdf')
#abcde123
#12345kdf
#alex???
#1l5x
print('alex'.translate(password))

print('alex'.replace('l',"L"))
print('alexl'.replace('l',"L",1))




print('alex li'.rfind('1'))
print('aleEXSSnn'.title())
#Aleexssnn

  

#split
print('alex is LI'.split())
#['alex', 'is', 'LI']

print('alex is LI'.split('l'))
#['a', 'ex is LI']

print('1+2+4'.split('+'))
#['1', '2', '4']

print('1+2\n+4'.splitlines())
#['1+2', '+4']

print('1+2\n+4'.split())
#['1+2', '+4']

  

5.字典 dict

#初始化dict
dic = dict.fromkeys([6,7,8])
print(dic)
#{8: None, 6: None, 7: None}

dic1 = dict.fromkeys([6,7,8],'test')
print(dic1)
#{8: 'test', 6: 'test', 7: 'test'}


dic2 = dict.fromkeys([6,7,8],[11,{'alex':33},'ssss'])
print(dic2)
#{8: [11, {'alex': 33}, 'ssss'], 6: [11, {'alex': 33}, 'ssss'], 7: [11, {'alex': 33}, 'ssss']}

  

info = {
    'name':'alex',
    'age':'23',
    'job':'it',
    'sal':'1111',
}

print(info) # k :v   无序的

  

#key value item
print(info.keys())
print(info.values())
print(info.items())
# dict_keys(['job', 'name', 'sal', 'age'])
# dict_values(['it', 'alex', '1111', '23'])
# dict_items([('job', 'it'), ('name', 'alex'), ('sal', '1111'), ('age', '23')])

  

#查找
print(info.get('sss',None))
#print(info['sss']) #KeyError: 'sss'

print('23' in info)#False

print('age' in info)#True

  

#改 增
info['age']='66'
print(info)

info['snake']='we'
print(info)

  

#删除

del info['age']
print(info)

info.pop('name')
print(info)

  

#合并 两个字典
b = {
    'stu':'jack',
    'saving':'2000',
    'course':'python',
}
info.update(b)
print(info)

#{'snake': 'we', 'sal': '1111', 'stu': 'jack', 'course': 'python', 'saving': '2000', 'job': 'it'}

  

 

#嵌套  三维字典
av_msg = {
    'we':{
          'top':['957','v'],
          'jug':['condi','mlxg'],
          'mid':['xiye','xiaohu']
          },
    'edg':{
        'xia':['zet','zhao'],
        'jug':['loli','clearlove'],
        'top':['mouse','audi']
    },
    'rng':{
        'top':['letme','kornal'],
        'xia':['y4','uzi'],
        'fuzhu':['ming','ning']
    }
}

#修改
print(av_msg)
av_msg['rng']['top'][0]='longlong'
print(av_msg)

#增加
av_msg.setdefault('ig',{'top':['sky','skey']})  #增加一条
av_msg.setdefault('rng',{'top':['sky','skey']})  #如果存在rng,则不添加
print(av_msg)



#循环打印key
for k in av_msg:
    print(k)


#ig
# edg
# we
# rng


#循环打印value
for v in av_msg:
    print(av_msg[v])


#字典转换成列表,不推荐使用
for k,v in av_msg.items():
    print(k,v)





# for index,item in enumerate(av_msg)
for index,item in enumerate(av_msg):
    print(index,item)

# 0 rng
# 1 ig
# 2 we
# 3 edg

for index,item in enumerate(av_msg):
    print(index,item,av_msg[item])
#0 edg {'xia': ['zet', 'zhao'], 'jug': ['loli', 'clearlove'], 'top': ['mouse', 'audi']}
#1 ig {'top': ['sky', 'skey']}
#2 rng {'top': ['longlong', 'kornal'], 'xia': ['y4', 'uzi'], 'fuzhu': ['ming', 'ning']}
#3 we {'mid': ['xiye', 'xiaohu'], 'top': ['957', 'v'], 'jug': ['condi', 'mlxg']}

  

作业三:多级菜单

三级菜单
可依次选择进入各子菜单
所需新知识点:列表、字典
'''
info ={
    'China':{
        '陕西':{
            '西安':['小寨','雁塔','高新'],
            '咸阳':['乾陵','昭陵','武陵'],
            '渭南':['渭水','华山','黄河'],
        },
        '江苏':{
            '昆山':['统一','康师傅','三一'],
            '上海':['机场','英语','明珠'],
            '南京':['大桥','长江','渔船'],
        },
        '北京':{
            '北京市':['长城','故宫','颐和园'],
            '天津':['炮台','海港','包子'],
            '烟台':['海滩','大海','海鲜'],
        },
    },

    'USA':{'埃塞尔州':{'洛杉矶':['湖人','火箭','勇士']}},
    'Europe':{'莱茵河':{'英国':['神奇女侠','希特勒','诺曼底']}}
}


while True:
    for item in info:
        print(item)

    choice_1 = input('choice_1 [q|.]>').strip()
    if choice_1 in info:

        while True:
            for i in info[choice_1]:
                print('\t',i)

            choice_2 = input('\tchoice_2 [q|e|.]>').strip()
            if choice_2 in info[choice_1]:
                while True:
                    for i in info[choice_1][choice_2]:
                        print('\t\t',i)


                    choice_3 = input('\t\tchoice_3 [q|e|.]>').strip()
                    if choice_3 in info[choice_1][choice_2]:
                        while True:
                            print('\t\t\t',info[choice_1][choice_2][choice_3])
                            choice_4 = input('this is bottom [ q | e]>')

                            if choice_4 == 'q':
                                break
                            elif choice_4 == 'e':
                                exit()
                    elif choice_3 == 'q':
                        break
                    elif choice_3 == 'e':
                        exit()

            elif choice_2 == 'q':
                break
            elif choice_2 == 'e':
                exit()

    elif choice_1 == 'q':
        exit()
View Code

 

 

'''
如何获取dict 下标对应的item
'''

  

posted @ 2017-10-03 00:19  venicid  阅读(281)  评论(0编辑  收藏  举报