PythonClassChy/python27HomeWork/python/FloraHomeWork_0222.py

219 lines
7.2 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
=================================
Author: Flora Chen
Time: 2020/2/22 19:27
-_- -_- -_- -_- -_- -_- -_- -_-
=================================
"""
"""
# 第一题:现有数据如下
users_title = ["name", "age", "gender"]
users_info = [['小明', 18, ''], ["小李", 19, ''], ["小美", 17, '']]
# 要求:请封装一个函数,上述两个列表作为参数传入,返回值为如下数据(提示:需要用到zip和for循环
users = [{'name': '小明', 'age': 18, 'gender': ''},
{'name': '小李', 'age': 19, 'gender': ''},
{'name': '小美', 'age': 17, 'gender': ''}]
"""
users_title = ["name", "age", "gender"]
users_info = [['小明', 18, ''], ["小李", 19, ''], ["小美", 17, '']]
def user_func(title, info):
users = []
for item in info:
users.append(dict(zip(title, item)))
return users
result = user_func(users_title, users_info)
# 按照老师题目中给出的格式输出
# new_result = 'users = [' + str(result[0]) + ',\n ' + str(result[1]) + ',\n ' + str(result[2]) + ']'
new_result = 'users = [{},\n{:>49},\n{:>49}]'.format(str(result[0]), str(result[1]), str(result[2]))
print(new_result)
# 弯弯绕绕的解题方法
# def user_func(title_len, *args):
# # 定义3个列表来接收新的列表
# users_title2 = []
# users_info2 = []
# users = []
#
# # 遍历传入的不定长参数,将值分情况保存到新列表中
# for item in args:
# if title_len <= 0:
# users_info2.append(item)
# else:
# users_title2.append(item)
# title_len -= 1
#
# # 对两个新列表进行打包,并转换成字典格式,然后保存在列表中
# for a in users_info2:
# users.append(dict(zip(users_title2, a)))
#
# # 返回新列表
# return users
#
# print(user_func(len(users_title), *users_title, *users_info))
"""
第二题:请封装一个函数,按要求实现数据的格式转换
# 传入参数: data = ["{'a':11,'b':2}", "[11,22,33,44]"]
# 返回结果res = [{'a': 11, 'b': 2}, [11, 22, 33, 44]]
# 通过代码将传入参数转换为返回结果所需数据,然后返回
"""
# 使用必备参数
def transform_data1(li):
res = []
for param in li:
res.append(eval(param))
return res
data = ["{'a':11,'b':2}", "[11,22,33,44]"]
print(transform_data1(data))
# 使用不定长参数
def transform_data2(*args):
res = []
for param in args:
res.append(eval(param))
return res
data = ["{'a':11,'b':2}", "[11,22,33,44]"]
print(transform_data2(*data))
"""
第三题当前有一个data.txt文件内容如下
数据aaa
数据bbb
数据ccc
数据ddd
# 要求:请将数据读取出来,保存为以下格式
{'data0': '数据aaa', 'data1': '数据bbb', 'data2': '数据ccc', 'data3': '数据ddd'}
# 提示思路:
#1、按行读取数据2、构造字典的键 3、打包为字典
# 注意点:读取出来的数据有换行符'\n',要想办法去掉
"""
# --------------------方法1--------------------
# 读取文件的内容
with open('data.txt', 'r', encoding='utf-8') as f:
data_value = []
data_key = []
datas = f.readlines()
for i in range(len(datas)):
data_key.append("data{}".format(i))
data_value.append(datas[i].replace('\n', ''))
data = dict(zip(data_key, data_value))
# --------------------方法2--------------------
# 读取数据,每一行作为一个元素放到列表中
with open('data.txt', 'r', encoding='utf-8') as f:
datas = f.readlines()
# 创建一个空字典
dic = {}
# 通过enumerate去获取列表中的数据和下标
for index, data in enumerate(datas):
key = 'data{}'.format(index)
value = data.replace('\n', '')
# 加入到字典中
dic[key] = value
# --------------------方法3--------------------
with open('data.txt', 'r', encoding='utf-8') as f:
data_value = []
data_key = ['data0', 'data1', 'data2', 'data3']
for i in f.readlines():
new_i = i.split('\n')
data_value.append(new_i[0])
data = dict(zip(data_key, data_value))
# 覆盖写入保存后的数据
with open('data.txt', 'w', encoding='utf-8') as f:
f.write(str(data))
"""
4、继续扩展石头剪刀布的游戏想办法把每次游戏结果都写入到txt文件中保存文件中写入内容格式如下
"""
import random
# --------------------方法1--------------------
# 猜拳小游戏
def game():
print('---石头剪刀布游戏开始---')
print('请按照下面的提示出拳:')
li = ['石头', '剪刀', '']
game_results = []
while True:
print('石头【1】剪刀【2】布【3】/结束游戏【4】')
user_num = int(input('请输入你的选项:'))
r_num = random.randint(1, 3)
print(r_num)
if 1 <= user_num <= 3:
if r_num == user_num:
res1 = '您的出拳为:{} 电脑出拳:{},平局'.format(li[user_num - 1], li[r_num - 1])
game_results.append(res1)
print(res1)
elif (user_num - r_num) == -1 or (user_num - r_num) == 2:
res2 = '您的出拳为:{} 电脑出拳:{},您胜利了'.format(li[user_num - 1], li[r_num - 1])
game_results.append(res2)
print(res2)
else:
res3 = '您的出拳为:{} 电脑出拳:{},您输了'.format(li[user_num - 1], li[r_num - 1])
game_results.append(res3)
print(res3)
elif user_num == 4:
res4 = '游戏结束!'
game_results.append(res4)
print(res4)
break
else:
res5 = '您出拳有误,请按规矩出拳!!'
game_results.append(res5)
print(res5)
return game_results
# 将猜拳小游戏的结果覆盖写入文件中
def save_game():
# 追加写入游戏结果
with open('game.txt', 'w', encoding='utf-8') as f:
for game_result in game():
f.write(game_result + '\n')
# 调用函数
# save_game()
# --------------------方法2--------------------
with open('game.txt', 'w', encoding='utf-8') as f:
print('---石头剪刀布游戏开始---')
print('请按照下面的提示出拳:')
li = ['石头', '剪刀', '']
game_results = []
while True:
print('石头【1】剪刀【2】布【3】/结束游戏【4】')
user_num = int(input('请输入你的选项:'))
r_num = random.randint(1, 3)
print(r_num)
if 1 <= user_num <= 3:
if r_num == user_num:
f.write('您的出拳为:{} 电脑出拳:{},平局\n'.format(li[user_num - 1], li[r_num - 1]))
elif (user_num - r_num) == -1 or (user_num - r_num) == 2:
f.write('您的出拳为:{} 电脑出拳:{},您赢了\n'.format(li[user_num - 1], li[r_num - 1]))
else:
f.write('您的出拳为:{} 电脑出拳:{},您输了\n'.format(li[user_num - 1], li[r_num - 1]))
elif user_num == 4:
f.write('游戏结束!\n')
break
else:
f.write('您出拳有误,请按规矩出拳!\n')