python基础入门二

写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
name = ” aleX”
1)移除 name 变量对应的值两边的空格,并输出处理结果
2) 判断 name 变量对应的值是否以 “al” 开头,并输出结果

3) 判断 name 变量对应的值是否以 “X” 结尾,并输出结果

4) 将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
5) 将 name 变量对应的值根据 “l” 分割,并输出结果。
6) 将 name 变量对应的值变大写,并输出结果

7) 将 name 变量对应的值变小写,并输出结果

8) 请输出 name 变量对应的值的第 2 个字符?
9) 请输出 name 变量对应的值的前 3 个字符?
10) 请输出 name 变量对应的值的后 2 个字符?

11) 请输出 name 变量对应的值中 “e” 所在索引位置?

12) 获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。

name = " aleX"


print(name.strip())

print(name.startswith('al'))

print(name.endswith('X'))

print(name.replace('l','p'))
print(name.split('l'))
print(name.upper())
print(name.capitalize())
print(name[1])
print(name[:3])
print(name[3:])
print(name.index('e'))
print(name[:-1])
  1. 有列表data=[‘alex’,49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量
data=['alex',49,[1900,3,18]]
name = data[0]
age = data[1]
birth = data[2]
print("名字是{0}年龄是{1}出生年月是{2}".format(name,age,birth))
  1. 用列表模拟队列(队列是先进先出,类似于自动扶梯)
dui = [1,2,3,4,5,6]
dui.insert(len(dui),'ll')
print(dui)
dui.pop(0)
print(dui)
  1. 用列表模拟堆栈(堆栈先进后出,类似于喝酒喝吐了)
zhan = [1,2,3,4,5,6]
zhan.insert(len(zhan),'ll')
print(zhan)
zhan.pop()
print(zhan)
  1. 有如下列表,请按照年龄排序(涉及到匿名函数)
l=[
    {'name':'alex','age':84},
    {'name':'oldboy','age':73},
    {'name':'egon','age':18},
]

l.sort(key=lambda item:item['age'])
print(l)

1 有如下值集合 [11,22,33,44,55,66,77,88,99,90…],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中
即: {‘k1’: 大于66的所有值, ‘k2’: 小于66的所有值}

l = [11,22,33,44,55,66,77,88,99,90,50,40,100]

dic = {'k1':[],'k2':[]}
for num in l:
    if num > 66:
        dic['k1'].append(num)
    else:
        dic['k2'].append(num)

print(dic)

2 统计s=’hello alex alex say hello sb sb’中每个单词的个数
结果如:{‘hello’: 2, ‘alex’: 2, ‘say’: 1, ‘sb’: 2}
s=’hello alex alex say hello sb sb’
ll = s.split() # 以空格区分
集合去重实现#
res = set(ll) # 去重
dic = dic.fromkeys(res) #初始化字典
for k in res:
dic[k] = ll.count(k) #填入数据
print(dic)
字典的setdefault方法实现#
dic = {}
for k in ll:
dic.setdefault(k,ll.count(k))
print(dic)

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

l=['a','b',1,'a','a']
new = set(l)
print(new)

2.在上题的基础上,保存列表原来的顺序

l=['a','b',1,'a','a']
new = set()
res = []
for d in l:
    if d not in new:
        new.add(d)
        res.append(d)
print(res)

3.去除文件中重复的行,肯定要保持文件内容的顺序不变


file = open('C:\Users\liuliangliang\Desktop\UserLoginServiceImplTest.java','r')
file = file.readlines()
s = set()
res = []
for line in file:
    if line in file:
        print(line)
        if line  not in s:
            s.add(line)
            res.append(line)

write = open('C:\Users\liuliangliang\Desktop\UserLoginServiceImplTest','w')
write.writelines(res)

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'},
]

s = set()
res = []

for i in l:
    val = (i['name'],i['age'],i['sex'])
    if val not in s:
        print(val)
        s.add(val)
        res.append(i)
print(res)
print(s)
  1. 文件a.txt内容:每一行内容分别为商品名字,价钱,个数,求出本次购物花费的总钱数

apple 10 3

tesla 100000 1

mac 3000 2

lenovo 30000 3

chicken 10 3

import os

### 获取当前文件路径
pwd = os.getcwd()
### 得到存储用户信息的文件路径
filedir = pwd + '\qingdan'
### 判断信息文件是否存在,存在即取出并转换成字典类型数据,否则提示文件不存在退出
if os.path.exists(filedir):
    wp = open(filedir, 'r',encoding='utf-8')
    sett = wp.readlines()
    print(sett)
    wp.close()
else:
    print("文件不存在!")
    exit()
last = 0
for i in sett:
    res = i.split()
    count = int(res[1])*int(res[2])
    last = last + count
print(last)

需求:

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



import json
import os

# 获取当前文件路径
pwd = os.getcwd()
# 得到存储用户信息的文件路径
filedir = pwd + '\dic'
listdir =pwd + '\list'
# 判断信息文件是否存在,存在即取出并转换成字典类型数据,否则提示文件不存在退出
if os.path.exists(filedir) and os.path.exists(listdir):
    wp = open(filedir, 'r')
    sett = wp.read()
    dic_user = json.loads(sett)
    wp.close()
    sp = open(listdir,'r')
    shop = sp.read()
    dic_product = json.loads(shop)
    sp.close()
else:
    print("文件不存在!")
    exit()

Tag = True
while Tag:

    name = input("请输入用户名:")
    # 判断用户名是否存在于文件中
    if name not in dic_user.keys():
        print("用户不存在!")
        continue
    passwd = input("请输入用户密码:")
    # 判断用户名密码是否正确
    if name in dic_user.keys() and passwd == dic_user.get(name).get('passwd'):
        list_info = [{"username": name}]
        cmd = input("输入你的工资")
        last = int(cmd)
        while Tag:

            print(dic_product)
            # cap,num = input("___输入您想要购买的物品编号和个数以空格分开:如'001 2'").split()
            cap = input("输入您所购买的物品编码:").strip()

            if cap  not in dic_product :
                print("请输入正确的物品编码")
                continue

            num = input("输入您所购买物品的数量:").strip()

            if cap  not in dic_product or not num.isdigit():
                print("请输入正确的物品编码或购买数!")
                continue

            account = int(dic_product[cap][1]) * int(num)
            if  account <= last:
                last = last - account

                list_info.append({"product":dic_product[cap],"num":num})
                quit = input("购买成功,退出输入q,继续输入y")
                if quit == 'q':
                    Tag = False
                    continue
                else:
                    continue
            else:

                addin = input("余额不足!充值输入y,退出输入q")
                if addin == 'y':
                    add = input("输入充值金额:").strip()
                    last = int(last) + int(add)
                    print("余额为%d" %last)
                if addin == 'q':
                    Tag =False
                    continue

        list_info.append({"last_money": last})
        for i in list_info:
            print(i)
        continue
    else:
        if name in dic_user.keys():
            print("用户名存在,密码错误")

            dic_user[name]['count'] += 1
            if dic_user[name]['count'] == 3:
                print("输入错误三次,退出程序")
                Tag = False

input(" ")

要求:

打印省、市、县三级菜单
可返回上一级
可随时退出程序

import json
import os

# 获取当前文件路径
pwd = os.getcwd()
# 得到存储用户信息的文件路径
filedir = pwd + '\www'
# 判断信息文件是否存在,存在即取出并转换成字典类型数据,否则提示文件不存在退出
if os.path.exists(filedir):
    wp = open(filedir, 'r',encoding='utf-8')
    sett = wp.read()
    data = json.loads(sett)
    wp.close()
else:
    print("文件不存在!")
    exit()
# 定义一个字典类型,存放修改后的字典
diction = data
# 定义一个列表类型,存放修改后的字典
listion = [data]

while True:
# 当字典为空时,提示没有下级,显示上一层内容
    if diction == {}:
        print("没有下级了!")
        diction = listion[-1]
        listion.pop()

    for key in diction:
        print(key,end=' |')
    agent = input("\n输入上述名称查询,输入r返回上一层,输入q退出:")
# 如果输入信息存在当前字典中,将当前的字典追加进入列表,将当前字典转换成下级字典
    if agent in diction:
        listion.append(diction)
        diction = diction[agent]
# 如果输入信息是r, 判断列表为空时提示没有上一级,不为空返回上一级,当前字典转换成上一级字典
    elif agent == 'r':
        if len(listion) == 0:
            print("没有上一级了!")
        else:
            diction = listion[-1]
            listion.pop()
# 如果输入信息是q,退出程序
    elif agent == 'q':
        break
    else:
        print("输入有误,重新输入")









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章