python字符类型小练习

写代码,有如下变量,请按照要求实现每个功能
name = " aleX"
#1)    移除 name 变量对应的值两边的空格,并输出处理结果
print(name.strip())
#2)    判断 name 变量对应的值是否以 "al" 开头,并输出结果print(name.startswith('al'))
#3)    判断 name 变量对应的值是否以 "X" 结尾,并输出结果print(name.endswith('x'))
#4)    将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
print(name.replace('l','p'))
#5)    将 name 变量对应的值根据 “l” 分割,并输出结果。
print(name.split('l'))
#6)    将 name 变量对应的值变大写,并输出结果print(name.upper())
#7)    将 name 变量对应的值变小写,并输出结果print(name.lower())
#8)    请输出 name 变量对应的值的第 2 个字符?
print(name[2])
#9)    请输出 name 变量对应的值的前 3 个字符?
print(name[0:3])
#10)    请输出 name 变量对应的值的后 2 个字符?print(name[-1:-3:-1])
print(name[-3:])
#11)    请输出 name 变量对应的值中 “e” 所在索引位置?print(name.index('e'))
#12)    获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
print(name[0:-1])
1. 取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量

data=['alex',49,[1900,3,18]]
print(data[0])
print(data[2][0])

2. 用列表模拟队列
l1=[]
l1.append('name')
l1.append('age')
l1.append('sex')
print(l1)
print(l1.pop())
print(l1.pop())
print(l1.pop())
3. 用列表模拟堆栈
####方法1:使用list反转命令(reverse)
l2=[]
l2.append('name')
l2.append('age')
l2.append('sex')
l2.reverse()
print(l2)
print(l2.pop())
print(l2.pop())
print(l2.pop())
####方法2:使用insert插入,每次都在index0之前插入
l3=[]
l3.insert(0,'name')
l3.insert(0,'age')
l3.insert(0,'sex')
print(l3)
print(l3.pop(0))
print(l3.pop(0))
print(l3.pop(0))
4. 有如下列表,请按照年龄排序(涉及到匿名函数)
l4=[
    {'name':'alex','age':84},
    {'name':'oldboy','age':73},
    {'name':'egon','age':18},
]
l4.sort(key=lambda item:item['age'])    ####匿名函数,lambda
print(l4)
简单购物车

实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入 

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
l5={}
tag=True
while tag:
    for name in msg_dic:
        print('name:%s\t\tprice:%s'%(name,msg_dic[name]))
    buy_name=input('name>>>').strip()
    if buy_name not in msg_dic.keys() or buy_name is None:
        print('输入商品名非法,请重新输入')
        continue
    while tag:
        for name in msg_dic:
            print('name:%s\t\tprice:%s' % (name, msg_dic[name]))
        count=input('num>>>').strip()
        if not count.isdigit():continue
        l5.setdefault(buy_name,[count,int(count)*int(msg_dic[buy_name])])
        print(l5)
        tag=False

#方法1:   
l5=[]
msg=(msg_dic.items())
print(msg)
while True:
    for key,items in msg:
    #print('name:{name} price:{price}'.format(name=key,price=items))   
        print('name:%s \t\t price:%s' %(key,items))
    choice=input('输入商品名:').strip()
    if not choice or choice not in msg_dic:
        print('输入商品非法,请重新输入')
    count=input('输入商品数量:').strip()
    if not count.isdigit():continue
    l5.append((choice,msg_dic[choice],count,msg_dic[choice] * int(count)))
    print(l5)
    break
#方法2:
dic_shop={}
while True:
    print(msg_dic)
    name = input('输入商品名:').strip()
    if name not in msg_dic:
        print('输入的商品不存在,请输入商品栏的商品')
        continue
    else:
        while True:
            num = input('输入购买的件数:').strip()
            if num.isdigit() == False:
                print('输入件数非法,请重新输入')
                continue
            else:
                print('购买<%s>件' % num)
                num = int(num)
                stop_list = dic_shop.setdefault('shop', [])
                stop_list.append(name)
                stop_list.append(num)
                stop_list.append(msg_dic[name] * num)
                print(dic_shop)
                break
    break
1 有如下值集合,将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中

即: {‘k1’: 大于66的所有值, ‘k2’: 小于66的所有值}

a=[11,22,33,44,55,66,77,88,99]
l6={'k1':[],'k2':[]}
for i in a:
    if i >66:
        l6['k1'].append(i)
    elif i < 66:
        l6['k2'].append(i)
    else:
        continue
print(l6)
2 统计s=’hello alex alex say hello sb sb’中每个单词的个数

结果如:{‘hello’: 2, ‘alex’: 2, ‘say’: 1, ‘sb’: 2}

#方法1:使用setdefault追加,count统计
s='hello alex alex say hello sb sb'
l7=s.split()
print(l7)
dic={}
for i in l7:
    dic.setdefault(i,l7.count(i))
print(dic)
#方法2:dict直接赋值,count统计
s='hello alex alex say hello sb sb'
l7=s.split()
dic2={}
for i in l7:
    dic2[i]=l7.count(i)
print(dic2)
#方法3:使用if in 判断vlues是否存在于dict中。
s='hello alex alex say hello sb sb'
l7=s.split()
dic3={}
for i in l7:
    if i  in dic3:
        dic3[i]+=1
    else:
        dic3[i]=1
print(dic3)
#方法4:使用集合,减少循环
s='hello alex alex say hello sb sb'
dic={}
l7=s.split()
l7_1=set(l7)
for i in l7_1:
    dic[i]=s.count(i)
print(dic)
一.关系运算
有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合

pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}

1. 求出即报名python又报名linux课程的学员名字集合

print(pythons & linuxs)

2. 求出所有报名的学生名字集合

print(pythons | linuxs)

3. 求出只报名python课程的学员名字

print(pythons - linuxs)

4. 求出没有同时这两门课程的学员名字集合

print(pythons ^ linuxs)

去重
1. 有列表l=[‘a’,’b’,1,’a’,’a’],列表元素均为可hash类型,去重,得到新列表,且新列表无需保持列表原来的顺序
#方法1:使用集合

l=['a','b',1,'a','a']
print(set(l))
2.在上题的基础上,保存列表原来的顺序
#方法1:使用not in 不在列表则追加:
l=['a','b',1,'a','a']
l8=[]
s=set()
for i in l:
    if i not in s:
        s.add(i)
        l8.append(i)
print(l8)
3.去除文件中重复的行,肯定要保持文件内容的顺序不变
import os
with open('db.txt','r',encoding='utf-8') as read_f,open('.db.txt.swap','w',encoding='utf-8')as write_f:
    s=set()
    for line in read_f:
        if line not in s:
            s.add(line)
            write_f.write(line)
os.remove('db.txt')
os.rename('.db.txt.swap','db.txt')
4.有如下列表,列表元素为不可hash类型,去重,得到新列表,且新列表一定要保持列表原来的顺序
l=[
    {'name':'egon','age':18,'sex':'male'},
    {'name':'alex','age':73,'sex':'male'},
    {'name':'egon','age':20,'sex':'female'},
    {'name':'egon','age':18,'sex':'male'},
    {'name':'egon','age':18,'sex':'male'},
]
l8=[]
s=set()
for dic in l:
    vars=(dic['name'],dic['age'],dic['sex'])
    if vars not in s:
        l8.append(dic)
print(l8)
#定义函数,既可以针对可以hash类型又可以针对不可hash类型  
def func(items,key=None):
    s=set()
    for item in items:
        val=item if key is None else key(item)
        if val not in s:
            s.add(val)
            yield item
print(list(func(l8,key=lambda dic:(dic['name'],dic['age'],dic['sex']))))
三级菜单练习:

流程图:
这里写图片描述

china={'北京':
              {'昌平':{'霍营':
                              {'饭店':{},'霍营小学':{}},'西二旗':{'百度科技园':{},'联想公司':{}}
                      },
              '丰台':{'新宫':
                              {'家':{},'家门口':{}}
                      }
              },
       '山西':{'太原':{'小店':{'山大':{}},'迎泽':{'迎泽公园':{}}},'运城':{'闻喜':{},'夏县':{}}}
       }

tag=True
while tag != False:
       for x in china:print('fri:%s'%x)
       fri=input('fri>>>').strip()
       if fri  in list(china.keys()):
              china_xx=china[fri]
              while tag:
                     for xx in china_xx:print('sec:%s'%xx)
                     sec=input('sec>>>').strip()
                     if sec in list(china_xx.keys()):
                            china_xxx=china_xx[sec]
                            while tag:
                                   for xxx in china_xxx:print('thi:%s'%xxx)
                                   thi = input('thi>>>').strip()
                                   if thi in list(china_xxx) or not thi:
                                          china_xxxx=china_xxx[thi]
                                          while tag:
                                                 for xxxx in china_xxxx:print('fou:%s'%xxxx)
                                                 fou=input('fou>>>').strip()
                                                 if fou == 'exit':tag=False
                                                 elif fou == 'r':break
                                                 else: continue
                                   elif thi == 'exit': tag = False
                                   elif thi == 'r':
                                          break
                     elif sec == 'exit': tag = False
                     elif sec == 'r':
                            break
       elif fri == 'exit':tag=False
       else:continue
作业二:请闭眼写出购物车程序

需求:
用户名和密码存放于文件中,格式为:egon|egon123
启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
流程图:
这里写图片描述

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
write_f=open('db.txt','w',encoding='utf-8')
write_f.writelines('egon|egon123')
write_f.close()
read_f= open('db.txt','r',encoding='utf-8')
for lines in read_f:
       l1=lines.split('|')
shop_list={}
tag=True
count=1
while tag and count <=3:
    user=input('name>>>').strip()
    count += 1
    if user != l1[0]:
           print('用户名不存在,请重新输入')
           continue
    else:
        passwd=input('password>>>').strip()
        if passwd != l1[1]:
           print('密码不正确,请重新输入')
           continue
        else:
            while tag:
                print('欢迎登陆xxx小店,祝您购物愉快!')
                salary=input('输入工资,愉快购物>>>').strip()
                while tag:
                    if not salary.isdigit():
                        print('工资一定为汉字')
                        continue
                    print('commdity\t\tprice')
                    print('--'*10)
                    for com in msg_dic:
                        print('%s\t\t%s'%(com,msg_dic[com]))
                    comm=input('comm>>>').strip()
                    if comm == 'exit':
                        tag = False
                    elif comm not in msg_dic:continue
                    else:
                        if int(salary) < int(msg_dic[comm]):
                            print('余额不足,请充值!')
                            continue
                        else:
                            while tag:
                                num=input('num>>>').strip()
                                if not num.isdigit():continue
                                if num == 'exit':
                                    tag=False
                                else:
                                    if int(salary) < int(msg_dic[comm]*int(num)):
                                        print('余额不足,请充值!')
                                        continue
                                    else:
                                        salary=(int(salary)-(int(msg_dic[comm]*int(num))))
                                        salary=str(salary)
                                        tot=(int(msg_dic[comm])*int(num))
                                        shop_list.setdefault(comm,[num,tot,salary])
                                        print('购买的商品是%s,总价%s,余额%s' %(comm,tot,salary))
                                        cont=input('是否继续购物(是/否):').strip()
                                        if cont == '是' or cont == 'y':
                                            print(shop_list)
                                            break
                                        else:
                                            print(shop_list)
                                            print('感谢您对本店大力支持!祝您生活愉快!')
                                            tag=False
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值