5.8 . 练习3_可变数据类型内置方法_文件操作练习

练习3

  1. 保存数字
    要求
  • 有如下值集合[1,22,33,44,55,66,77,88,99,90]
  • 将所有大于66的值保存至字典的第一个key中,小于66的值,保存至第二个key值中
  • 结果为‘{'k1':大于66的所有值,'k2':小于66的所有值}’
num_list=[1,22,33,44,55,66,77,88,99,90]

print(num_list)

#定义方式1
judge_dict={'k1':[],'k2':[]}

#定义方式2
# judge_dict['k1']=list()
# judge_dict['k2']=list()

for i in num_list:
    if i<66:
        judge_dict['k1'].append(i)
    elif i>66:
        judge_dict['k2'].append(i)
    
print(judge_dict)
[1, 22, 33, 44, 55, 66, 77, 88, 99, 90]
{'k1': [1, 22, 33, 44, 55], 'k2': [77, 88, 99, 90]}
  1. 统计每个单词出现次数

要求:

  • 统计s='hello apple jason thank thank jason sean say hello apple'
    *输出结果为:
#解法1
s='hello apple jason thank thank jason sean say hello apple' 

s_list=s.split()

s_dict=dict()

#去重作为关键字
s_list_set=set(s_list)
for i in s_list_set:
    s_dict[i]=0
print(s_dict)

#统计单词个数
for i in s_list:
    s_dict[i]+=1
print(s_dict)

{'jason': 0, 'thank': 0, 'say': 0, 'sean': 0, 'apple': 0, 'hello': 0}
{'jason': 2, 'thank': 2, 'say': 1, 'sean': 1, 'apple': 2, 'hello': 2}
#解法2
s='hello apple jason thank thank jason sean say hello apple' 
s_list=s.split()
s_dict=dict()
for i in s_list:
    if i in s_dict:
        s_dict[i]+=1
    else:
        s_dict[i]=1
print(s_dict)
{'hello': 2, 'apple': 2, 'jason': 2, 'thank': 2, 'sean': 1, 'say': 1}
  1. 统计文件中账单总花销

    要求:

    文件a.txt内容:每一行内容分别为商品名字,价钱,个数,要求本次购物花费的总钱数。

#a.txt 内容如下  

apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
#方法1

#打开文件同级目录用相对路径不同用绝对路径
#放同级目录下最好
#打开文件获取数据
with open(r'a.txt',mode='r',encoding='gbk') as f_r:
    data=f_r.read()

#处理数据,先按照换行符切割
data_spl1=data.split('\n')
print(data_list)

#定义空列表
lis=list()

#再按照空格切割列表元素,赋值给新列表
for i in range(0,len(data_list)):
    lis.append(data_list[i].split())
print(lis)

money=0 #定义总金额

for i in lis:
    money+=(int(i[1])*int(i[2]))
print(money)
['apple 10 3', 'tesla 100000 1', 'mac 3000 2', 'lenovo 30000 3', 'chicken 10 3']
[['apple', '10', '3'], ['tesla', '100000', '1'], ['mac', '3000', '2'], ['lenovo', '30000', '3'], ['chicken', '10', '3']]
196060
#方法2
money=0
with open(r'a.txt',mode='r',encoding='gbk') as f_r:
    for i in f_r:
        i_list=i.strip().split() #strip()也去除换行
        money+=int(i_list[1])*int(i_list[2])
    print(money)
196060
  1. 升级版猜年龄游戏

    要求:

    在上次猜年龄的基础上,把用户获奖信息存入到文件中

#猜数字游戏
import random
from pickletools import string1

# age =random.randint(10,20) #可以选择随机数作为答案,增加可玩性
age=10

count=0
user_login_dict=dict()

#注册
user_register_choice=input('register?y or n>>')
if user_register_choice=='y':

    print('Please register first!'.center(50, '-'))

    #保存注册信息到文件
    with open(r'username.txt',mode='a',encoding='utf-8') as f_a:
        user=input('username>>')
        psd=input('password>>')
        user_login_dict[user] = psd
        f_a.write(f'{user}:{psd}\n')


#登录
print('Welcome to login system!'.center(50, '-'))

username=dict()

#到用户登录信息文件中拿到用户名和密码并处理,保存为字典,方便查找匹配
with open(r'username.txt',mode='r',encoding='utf-8') as f_r:
    for i in f_r:
        name=i.strip().split(':')[0]
        pwd=i.strip().split(':')[1]
        username[name]=pwd

#输入用户名和密码
user_login_username=input('username>>')
user_login_pwd=input('password>>')

#验证用户名密码
if user_login_username in username and user_login_pwd==username.get(user_login_username):
    print('-' * 50)
    # 登陆成功开始游戏
    print('Welcome to the game!'.center(50, '-'))
    while count<3:
        inp_age = input("age input>>")
        if not inp_age.isdigit():
            continue
        inp_age=int(inp_age)
        if age == inp_age:
            print("yes")

            #获取奖品
            prize_dict=dict()
            prize_note=dict()
            with open(r'a.txt','r',encoding='utf-8') as f_r_p:
               for k,v in enumerate(f_r_p):
                   # enumerate() -> (索引,元素)
                   prize_dict[k]=v.strip().split()[0]
                   prize_note[v.strip().split()[0]]=0

               print(prize_note)

            #选择奖品,设置选择多个奖品可加入循环语句
            prize_choice=int(input(f"prize choice{prize_dict},无需礼物请输入'N' or 'n'>>"))
            if prize_choice == 'N' or prize_choice == 'n':
                break
            prize_note[prize_dict[prize_choice]]+=1

            #记录奖品信息到prize.txt文件
            with open(r'prize.txt','w',encoding='utf-8') as f_w_p:
                f_w_p.write(str(prize_note))
             
            #获取奖品完成退出系统
            break


        elif inp_age < age:
            print("small")
        else:
            print("big")
        count+=1

        #是否继续游戏
        if count==3:
            choice=input('continue? y or n>>')
            if choice=='y':
                count=0
else:
  print('Username or password error!!!')


#上述代码重复太多,如报错,修改较麻烦
#函数可解决代码重复、扩展性差,并且提高鲁棒性
posted @ 2025-08-17 20:09  bokebanla  阅读(6)  评论(0)    收藏  举报