#1、使用while循环输出1 2 3 4 5 6     8 9 10
# count=1
# while count<11:
#     if count ==7:
#         count+=1
#         continue
#     print(count)
#     count+=1
#1、使用while循环输出1 2 3 4 5 6     8 9 10
# count=1
# while count<11:
#     if count !=7:
#         print(count)
#     count+=1
#
# #2、求1-100的所有数的和
# count=1
# res=0
# while count<=100:
#     res+=count
#     count+=1
# print(res)
#
# #2、求1-100的所有数的和
# res=0
# for i in range(1,100):
#     res+=i
# print(res)
#
# #3、输出 1-100 内的所有奇数
# count=1
# while count<=100:
#     if count%2==1:
#         print(count)
#     count+=1
#
# #4、输出 1-100 内的所有偶数
# count=1
# while count<=100:
#     if count%2==0:
#         print(count)
#     count+=1
#
# #5、求1-2+3-4+5 ... 99的所有数的和
# count=1
# res=0
# while count<=99:
#     if count%2==0:
#         res-=count
#     else:
#         res+=count
#     count+=1
# print(res)

#6、用户登陆(三次机会重试)
# count=1
# while count<3:
#     u=input('u>>>:')
#     p=input('p>>>:')
#     if u=='egon'and p=='123':
#         print('login ok')
#         break
#     count+=1


#6、用户登陆(三次机会重试)
# count=0
# while True:
#     if count==3:
#         print('try too many times')
#         break
#     u=input('u>>>:')
#     p=input('p>>>')
#     if u=='fang' and p =='123':
#         print('login ok')
#         break
#     count+=1
#



#2:编写while循环,利用索引遍历出每一个字符
# msg='hello egon 666'
# count=0
# while count< len(msg):
#     print(msg[count])
#     count+=1

##1:编写for循环,利用索引遍历出每一个字符
# msg='hello egon 666'
# count=1
# for count in range(len(msg)):
#     print(msg[count])
#     count+=1

#3:msg='hello alex'中的alex替换成SB
# msg='hello alex'
# print(msg.replace('alex','SB'))

#msg='/etc/a.txt|365|get'
# #将该字符的文件名,文件大小,操作方法切割出来
# msg='/etc/a.txt|365|get'
# a=msg.split('|')
# print(a)
#
# #5.编写while循环,要求用户输入命令,如果命令为空,则继续输入
# tag5 = True
# while tag5:
#     cmd5 = input('>>>:')
#     if cmd5 == 'q':
#         tag5 = False
#         continue
#     print(cmd5)

#.编写while循环,让用户输入用户名和密码,如果用户为空或者数字,则重新输入
#
# tag6 = True
# while tag6:
#     usr6_inp = input('请输入用户名:')
#     pass6_inp = input('请输入命令:')
#     if usr6_inp == '' or usr6_inp.isdigit():
#         continue
#     else:
#         print('登录成功,%s!'%(usr6_inp))
#         tag6 = False
# #
#
#
# #7.编写while循环,让用户输入内容,判断输入的内容以alex开头的,则将该字符串加上_SB结尾
#
# tag7 = True
# while tag7:
#     work7 = input('请输入用户名:')
#     if work7 == 'alex':
#         print(work7+'SB')
#         tag7 = False
#         continue
#     else:
#         print(work7+'你好!')
#         break
#

'''
1.两层while循环,外层的while循环,让用户输入用户名、密码、工作了几个月、每月的工资(整数),用户名或密码为空,或者工作的月数不为整数,或者
月工资不为整数,则重新输入
2.认证成功,进入下一层while循环,打印命令提示,有查询总工资,查询用户身份(如果用户名为alex则打印super user,如果用户名为yuanhao或者wupeiqi
则打印normal user,其余情况均打印unkown user),退出功能
3.要求用户输入退出,则退出所有循环(使用tag的方式)


运行效果如下:
user: egon
password: 123
work_mons: 12
salary: 10000

            1 查询总工资
            2 查询用户身份
            3 退出登录

>>: 1
总工资是: 120000.0

            1 查询总工资
            2 查询用户身份
            3 退出登录

>>: 2
unkown user

            1 查询总工资
            2 查询用户身份
            3 退出登录

>>: 3
'''


# tag8 = True
# while tag8:
#     user_inp = input('请输入用户名:')
#     if user_inp == '':
#         print('输入错误,请重新输入!')
#         continue
#     password_inp = input('请输入密码:')
#     if password_inp == '':
#         print('输入错误,请重新输入!')
#         continue
#     work_mons_inp = input('请输入工作的月份')
#     if not work_mons_inp.isdigit():
#         print('输入错误,请重新输入!')
#         continue
#     salary_inp = input('请输入月薪')
#     if not salary_inp.isdigit():
#         print('输入错误,请重新输入!')
#         continue
#     print('user:' + user_inp)
#     print('password:' + password_inp)
#     print('work_mons:' + work_mons_inp)
#     print('salary:' + salary_inp)
#     while tag8:
#         choice_inp = input('请输入你要执行的操作:(1、查询总工资 2、查询用户身份 3、退出)')
#         if choice_inp == '1':
#             work_mons_inp = int(work_mons_inp)
#             salary_inp = int(salary_inp)
#             sum_salary = work_mons_inp * salary_inp
#             print(sum_salary)
#         elif choice_inp == '2':
#             if user_inp == 'alex':
#                 user_id = 'super user'
#             elif user_inp == 'wupeiqi‘ or user_inp == ‘yuanhao':
#                 user_id = 'normal user'
#             else:
#                 user_id = 'unknowuser'
#             print(user_id)
#         elif choice_inp == '3':
#             print('欢迎使用,下次再见!')
#             tag8 = False

# 一、元素分类
#
# 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
# 即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}


# li = [11,22,33,44,55,66,77,88,99,90]
# person = {">66":[],"<=66":[]}
# for i,j in enumerate(li,0) :
#
#     if int(j) > 66 :
#         person[">66"].append(j)
#     else :
#         person["<=66"].append(j)
#
# print(person)
# 二、查找
# 查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
# li = ["alec", " aric", "Alex", "Tony", "rain"]
# tu = ("alec", " aric", "Alex", "Tony", "rain")
# dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
#
# for i in li:
#      v1 = i.strip()
#      if (v1.startswith('a')or v1.startswith('A')) and v1.endswith('c'):
#         print(v1)
#
# for i in tu:
#      v1 = i.strip()
#      if (v1.startswith('a')or v1.startswith('A')) and v1.endswith('c'):
#         print(v1)
#
# for i in dic.values():
#      v1 = i.strip()
#      if (v1.startswith('a')or v1.startswith('A')) and v1.endswith('c'):
#          print(v1)
# 三、输出商品列表,用户输入序号,显示用户选中的商品
#     商品 li = ["手机", "电脑", '鼠标垫', '游艇']
# li = ["手机", "电脑", '鼠标垫', '游艇']
# a = {}
# for i in range(1, len(li) + 1):
#    a[str(i)] = li[i - 1]
#
# print('商品列表')
# for i in a:
#    print(('{}:{} '.format(i, a[i])).ljust(32))
# print()
# print("输入您要查看的商品序号,l键退出")
#
# while True:
#    index = input('>>>:')
#    if index == 'l':
#         break
#    elif index in a:
#        print('您要查看的商品是:', a[index])
#    else:
#        print('请重新输入')
#
#
#
#
# def show_shopping_cart():
#    if len(shopping_cart) == 0:
#        print("购物车为空.")
#    else:
#        print("您已经购买的商品:")
#        print("商品编号  商品名称  商品价格")
#        for j in shopping_cart:
#            good = goods[int(j) - 1]
#            print("%s,%s,¥%.2f" % (j, good["name"], int(good["price"])))

# 四、购物车
# 功能要求:
#
# 要求用户输入总资产,例如:2000
# 显示商品列表,让用户根据序号选择商品,加入购物车
# 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
# 附加:可充值、某商品移除购物车
# goods = [
#     {"name": "电脑", "price": 1999},
#     {"name": "鼠标", "price": 10},
#     {"name": "游艇", "price": 20},
#     {"name": "美女", "price": 998},
# ]
# total_money = 0
# remaining_money = 0
# shopping_cart = []
#
# print("欢迎来到狂购商城")
# print("以下是这次狂购商品价格列表")
# count = 1
# for item in goods:
#    print(("%s: %s ¥%.2f  " % (count, item["name"], int(item["price"]))).ljust(35,))
#    count += 1
#
# while True:
#    res = input("请输入你的资产:")
#    if not res.isdigit():
#        print("输入有误,请重新输入")
#    else:
#        total_money = int(res)
#        remaining_money = total_money
#        print("您的总资产为:%s元" % total_money)
#        break
#
# print("温馨提示:输入商品编号直接购买,充值请按a,删除购物车商品请按b,退出请按c")
# while True:
#    res = input(">>>:")
#    if res in ["1", "2", "3", "4"]:
#        goods_price = goods[int(res) - 1]["price"]
#        if goods_price <= remaining_money:
#            remaining_money -= goods_price
#            print("购买成功,您的余额是%s元" % remaining_money)
#            shopping_cart.append(res)
#        else:
#            print("购买失败,余额不足,商品价格是%s元,您的余额是%s元" % (goods_price, remaining_money))
#            print("如需充值,请按a")
#    elif res == "a":
#        res = input("请输入充值金额:")
#        remaining_money += int(res)
#        print("充值成功,您的余额是:%s元" % remaining_money)
#    elif res == "b":
#        print('show_shopping_cart:')
#        print("请输入您要删除的商品编号,退出删除请按e")
#        while True:
#            delete_index = input(">>>:")
#            if delete_index == "e":
#                print("删除商品完成,您可以继续购物")
#                break
#            elif delete_index == "r":
#                print('show_shopping_cart:' )
#            elif delete_index in shopping_cart:
#                shopping_cart.remove(delete_index)
#                remaining_money += int(goods[int(delete_index) - 1]["price"])
#                print("删除成功,您的余额是:%s" % remaining_money)
#            else:
#                print("您的输入有误,查看购物车信息请按q,退出删除请按e")
#    elif res == "l":
#        print("谢谢使用,再见!")
#        break
#    elif res =='c':
#        break
#    else:
#        print("您的输入有误:")
# 选做题:用户交互,显示省市县三级联动的选择
#
# dic = {
#     "河北": {
#         "石家庄": ["鹿泉", "藁城", "元氏"],
#         "邯郸": ["永年", "涉县", "磁县"],
#     }
#     "河南": {
#         ...
#     }
#     "山西": {
#         ...
#     }


# dic = {
#     "河北":{
#         "石家庄" :["鹿泉","藁城","元氏"],
#         "邯郸" : ["永年","涉县","磁县"]
#     },
#     "河南":{
#         "郑州":["巩义","登封","新密"],
#         "开封":["金明","鼓楼","通许"]
#     },
#     "山西":{
#         "太原":["古交","清徐","阳曲"],
#         "大同":["天镇","阳高","广灵"]
#     }
# }
# ###定义颜色
# def get_color(text, color='red'):
#     """
#     将字符串格式化为带颜色内容
#     :param text: 接收字符串
#     :param color:默认红色
#     :return: ->str 返回带颜色的内容
#     """
#     color_table = {
#         "red": "\033[31m",
#         "green": "\033[32;1m",
#         "yellow": "\033[33;1m",
#         "purple": "\033[36;1m",
#         "end": "\033[0m",  # 结束符号
#     }
#     li = [color_table.get(color), str(text), color_table["end"]]
#     return ''.join(li)
#
# while True:
#     province = input('输入Q结束,输入你喜欢的省:')
#     if len(province) == 0:
#         print("不能为空!")
#         continue
#     elif province == 'Q':
#         exit()
#     elif province not in dic:
#         print('天朝的省份都不知道,打死你哥龟孙!!!')
#         continue
#     city_list=[]
#     for i in dic[province]:
#         city_list.append(i)
#     print(get_color('%s省包括:%s' % (province, city_list), 'green'))
#
#     while True:
#         city = input("输入Q结束:输入q返回,输入城市查看县:")
#         if city == 'q':
#             break
#         elif city == 'Q':
#             exit()
#         elif city in city_list:             #必须放倒最后否则下面的while不会被执行
#             township = dic[province][city]
#             print(get_color('%s县包括:%s' % (city,township),'yellow'))
#
#             while True:
#                 county = input("输入Q结束,输入q返回,输入县进入县:")
#                 if county == 'q':
#                         break
#                 elif county == 'Q':
#                     exit()
#                 elif county in township:
#                    print(get_color(('%s县欢迎您!!!' % county),'purple'))






"""
#练习一:
if True or False and False:
    print('yes')
else:
    print('no')
#输出结果为?为什么?

if (True or False) and False:
    print('yes')
else:
    print('no')

#输出结果为?为什么?
"""
# if True or False and False:
#     print('yes')
# else:
#     print('no')
#
# if (True or False) and False:
#     print('yes')
# else:
#     print('no')

"""
#练习二:编写if多分支,猜老男孩的年纪
"""

# age = 35
#
# user_input = input("猜猜看啊:").strip()  # 让用户输入猜的年龄
# user_input = int(user_input)  # input获取到的都是字符串类型,与int类型做比较需要转换成int类型
# if user_input > age:  # 如果猜的数比age大
#     print("大了!")
# elif user_input < age:  # 如果猜的数比age小
#     print("小了!")
# else:
#     print("对了!")  # 否则猜的数等于age
#
# age=57
# print('请输入老男孩的年龄')
# res=input('>>>: ').strip()
# res=int(res)
# if res>age:
#     print('大了')
# elif res<age:
#     print('小了')
# else:
#     print('对了')
#
"""
#练习三:用户输入用户名密码验证,验证通过后进入子循环,输入命令,命令若为q,则退出所有循环
"""
# name = "Alex"
# password = "1234"
# exit_flag = False
#
# while not exit_flag:
#     input_n = input("请输入用户名:").strip()
#     input_p = input("请输入密码:").strip()
#     if input_n == name and input_p == password:
#         while not exit_flag:
#             input_cmd = input("请输入命令:").strip()
#             if input_cmd.upper() == "Q":
#                 exit_flag = True
#                 break
#     else:
#         print("用户名或密码错误!")
#         continue

"""
#练习四:循环取出元组中所有元素:
方式一:while和for(按照索引),
方式二:不按照索引的方式
# t=(1,2,3,4,5,6,7,8,9)
"""
# t = (1, 2, 3, 4, 5, 6, 7, 8, 9)

# 方法一
# n = 0
# while n < len(t):
#     print(t[n])
#     n += 1
#
# for i in range(len(t)):
#     print(t[i])

# 方法二
# for i in t:
#     print(i)

"""
#练习五:循环读取列表以及子列表中所有元素
l=[1,2,[3,4],[5,6]]
"""
l = [1, 2, [3, 4], [5, 6]]
for i in l:
    # if type(i) == list:
    if isinstance(i, list):
        for j in i:
            print(j)
    else:
        print(i)


# 练习六:打印
'''
   *
  ***
 *****
*******
'''
#
# for i in range(1, 8, 2):  # 1 3 5 7
#     print(("*" * i).center(7))
#
# for i in range(1, 8, 2):  # 1 3 5 7
#     print(' '*(4-(i+1)//2)+'*'*i)
#

# 练习七:打印
'''
 *****
  ***
   *
'''

# for i in range(5, 0, -2):  # 5 3 1
#     print(("*" * i).center(7))

# for i in range(5,0,-2):  # 5 3 1
#     print(' '*(4-(i+1)//2)+'*'*i)


# 练习八:打印
'''
*
**
***
****
*****
'''

# for i in range(1, 6):
#     print("*" * i)

# 练习九:打印
'''
******
*****
****
***
**
*
'''

# for i in range(5, 0, -1):
#     print("*" * i)

"""
#练习十:编写登陆接口
基础需求:
让用户输入用户名密码
认证成功后显示欢迎信息
输错三次后退出程序
"""

# username = "Alex"
# password = "1234"
# n = 3
# while n > 0:
#     input_n = input("请输入用户名:").strip()
#     input_p = input("请输入密码:").strip()
#
#     if input_n == username and input_p == password:
#         print("Hello Alex!")
#     else:
#         print("输入错误!")
#     n -= 1
# else:
#     print("输错三次,再见!")

"""
#数据类型练习题:
#练习一:有十进制数n=10
转成二进制
转成八进制
转成十六进制
"""
# n = 10
# # 转成二进制
# n_2 = bin(10)
#
# # 转成八进制
# n_8 = oct(n)
#
# # 转成十六进制
# n_16 = hex(n)

"""
#练习二:与用户交互,要求用户输入年龄和薪资,
将用户输入的年龄转成整型,将用户输入的薪资转成浮点型
"""

# age = input("请输入年龄:").strip()
# salary = input("请输入薪资:").strip()
#
# age_int = int(age)  # 将年龄转换成整型
# salary = float(salary)  # 将薪资转成浮点型

"""
#练习三:
用户输入用户名,年纪,工作,爱好,格式化输出如下内容(使用%s和format两种方式)
------------ info of Alex Li -----------
Name  : Alex Li
Age   : 22
job   : Teacher
Hobbie: girl
------------- end -----------------
"""

# %s 方式
# s = """
# ------------ info of Alex Li -----------
# Name  : %s
# Age   : %s
# job   : %s
# Hobbie: %s
# ------------- end -----------------
# """

# name = input("请输入用户名:").strip()
# age = input("请输入年纪:").strip()
# job = input("请输入工作:").strip()
# hobbie = input("请输入爱好:").strip()
#
# print(s % (name, age, job, hobbie))


# format 方式
# s = """
# ------------ info of Alex Li -----------
# Name  : {}
# Age   : {}
# job   : {}
# Hobbie: {}
# ------------- end -----------------
# """
#
# name = input("请输入用户名:").strip()
# age = input("请输入年纪:").strip()
# job = input("请输入工作:").strip()
# hobbie = input("请输入爱好:").strip()
#
# print(s.format(name, age, job, hobbie))

"""
#练习四:
s='alex say hello'
切片取出say
切片取出倒数后两个字符
"""
# s = 'alex say hello'
# print(s[5:9])
# print(s[-2:])

"""
#练习五:
# 编写循环,让用户输入年纪,如果输入为空,或者不为数字,则重新输入
"""

# while True:
#     age = input("请输入年纪:").strip()
#
#     if age:  # 判断输入是否为空
#         if age.isdigit():  # 判断是不是数字
#             print("年纪:{}".format(int(age)))
#             break

"""
#练习六:
用列表模拟上电梯的流程(队列)
    循环生成一个1000个值的列表(入队)
    循环取走这个1000个值(出队)

"""

# q = []  # 定义一个列表
# for i in range(1000):
#     q.append(i)  # 入队
#
# for j in range(1000):
#     print(q[0])  # 依次出队
#
"""
用列表模拟把衣服放箱子里,然后取衣服的流程(堆栈)
    循环生成一个1000个值的列表(入栈)
    循环取走这个1000个值(出栈)
"""
# q = []
# for i in range(1000):
#     q.append(i)
#
# for j in range(1, 1001):
#     print(q[-j])

"""
#练习七:
dicta={'a':1,'b':2,'c':3,'d':'hello'}
dictb={'b':3,'c':2,'d':'world','f':10}
#两字典相加,不同的key对应的值保留,相同的key对应的值相加后保留,如果是字符串就拼接(字符串拼接'hello'+'world'得'helloworld')
# {'a': 1, 'b': 5, 'c': 5, 'd': 'helloworld', 'f': 10}
"""
# dicta = {'a': 1, 'b': 2, 'c': 3, 'd': 'hello'}
# dictb = {'b': 3, 'c': 2, 'd': 'world', 'f': 10}
#
# dic = {}  # 定义一个字典,存放最后的结果
# dic = dicta  # 先把dica的内容放到dic里
# for i in dictb:
#     if i in dic:  # 相同的key对应的值相加后保留
#         dic[i] += dictb[i]
#     else:  # 不同的key对应的值保留
#         dic[i] = dictb[i]
#
# print(dic)

"""
练习八:
a.实现用户输入用户名和密码,当用户名为seven且密码为123时,显示登录成功,否则登录失败!

b.实现用户输入用户名和密码,当用户名为seven且密码为123时,显示登录成功,否则登录失败,失败时允许重复输入三次

c.实现用户输入用户名和密码,当用户名为seven或alex且密码为123时,显示登录成功,否则登录失败,失败时允许重复输入三次
"""

# a、b 略,这里写个c的示例代码吧。。。不会偷懒的程序员就不是好助教。
# for i in range(3):
#     username = input("请输入用户名:").strip()
#     password = input("请输入密码:").strip()
#     # 判断,记得逻辑运算的优先级!!!先计算and再计算or,所以 'or' 这里要加个括号。
#     if (username.upper() == "ALEX" or username.upper() == "SEVEN") and password == "123":
#         print("登录成功!")
#     else:
#         print("用户名或密码错误!")

"""
练习九:
写代码

a.使用while循环实现输出2-3+4-5+6...+100的和
b.使用for循环和range实现输出1-2+3-4+5-6...+99的和
c.使用while循环实现输出1,2,3,4,5   7,8,9  11,12
d.使用while循环实现输出1-100内的所有奇数
e.使用while循环实现输出1-100内的所有偶数
"""
# a
# a = 2  # 用a去模拟2 3 4 5 ... 100
# ret_a = 0  # 结果放到ret_a
# while a <= 100:
#     if a % 2 == 0:  # 能被2整除就+
#         ret_a += a
#     else:
#         ret_a -= a
#     a += 1
# print(ret_a)
#
# # b
# b = 1  # 用b去模拟1 2 3 4 5 ... 99
# ret_b = 0  # 结果存放到ret_b
# while b < 100:
#     if b % 2 == 0:  # 能被2整除就-
#         ret_b -= 1
#     else:
#         ret_b += 1
#     b += 1
# print(ret_b)
#
# # c
# c = 1
# while c <= 12:
#     if c == 6 or c == 10:
#         c += 1
#         continue
#     else:
#         print(c)
#         c += 1

# d、e 略。。。

"""
练习十:
name = "alex"
a.移除name变量对应的值的两边的空格,并输出移除后的内容
b.判断name变量对应的值是否以"al"开头,并输出结果
c.判断name变量对应的值是否以"x"结尾,并输出结果
d.将name变量对应的值中的"l"替换为"p",并输出结果
e.将name变量对应的值根据"l"分割,并输出结果
f.请问,上一题e分割之后得到的值是什么类型
g.将name变量对应的值中变大写,并输出结果
h.将name变量对应的值中变小写,并输出结果
i.请输出name变量对应的值的第2个字符?
j.请输出name变量对应的值的前3个字符?
k.请输出name变量对应的值的后2个字符?
l.请输出name变量对应的值中"e"所在的索引位置?
"""

# name = "alex"
# # a
# print(name.strip())
#
# # b
# print(name.startswith("al"))
#
# # c
# print(name.endswith("x"))
#
# # d
# print(name.replace("l", "p"))
#
# # e
# print(name.split("l"))
#
# # f
# print("list类型")
#
# # g
# print(name.upper())
#
# # h
# print(name.lower())
#
# # i
# print(name[1])
#
# # j
# print(name[:3])
#
# # k
# print(name[-2:])
#
# # l
# print(name.index("e"))
#
"""
练习十一:
写代码,有如下列表,按照要求实现每一个功能
li = ['alex','eric','rain','eric','rain']
a.计算列表长度并输出
b.列表中追加元素"seven",并输出添加后的列表
c.请在列表的第1个位置插入元素"Tony",并输出添加后的列表
d.请修改列表第2个位置的元素为"Kelly",并输出修改后的列表
e.请删除列表中的元素"eric",并输出修改后的列表
f.请删除列表中的第2个元素,并输出删除元素的值和删除元素后的列表
g.请删除列表中的第3个元素,并输出删除元素后的列表
h.请删除列表中的第2至4个元素,并输出删除元素后的列表
i.请将列表所有的元素反转,并输出反转后的列表
"""
# li = ['alex', 'eric', 'rain', 'eric', 'rain']
#
# # a
# print(len(li))
#
# # b
# li.append("seven")  # 注意:append()操作的返回值是None,不是添加完元素的列表。能看到这里的都是天选之子。
# print(li)
#
# # c
# li.insert(0, "Tony")  # insert()注意事项同上
# print(li)
#
# # d
# li[1] = "Kelly"
# print(li)
#
# # e
# li.remove("eric")
# print(li)
#
# # f
# r = li[1]
# li.remove(r)
# print(li)
#
# # g
# li.remove(li[2])
# print(li)
#
# # h
# del li[1:5]  # 这样快一些
# li[1:5] = []  # 这样也行
# print(li)
#
# # i
# li.reverse()  # 这样行,注意返回值是None
# li[::-1]  # 这样也行,返回值就是反转后的新列表
# print(li)

"""
#练习十二:
取出列表中的名字,年龄,出生的年,月,日
data=['alex',49,[1900,3,18]]
# """
# data = ['alex', 49, [1900, 3, 18]]
# print("名字:", data[0])
# print("年龄:", data[1])
# print("出生年:", data[2][0])
# print("出生月:", data[2][1])
# print("出生日:", data[2][2])

"""
#练习十三:
去掉重复
names=['egon','alex','egon','wupeiqi']
"""
# names = ['egon', 'alex', 'egon', 'wupeiqi']
# names = list(set(names))
# names = ['egon', 'alex', 'egon', 'wupeiqi']
# names = list(dict.fromkeys(names))  # 当然也可以利用字典的key不能重复来去重。能看到这里的就是尼玛天才
# print(names)

"""
#练习十四:
去掉重复,且保证列表顺序与原来保持一致
names=['egon','alex','egon','wupeiqi']
"""
# names = ['egon', 'alex', 'egon', 'wupeiqi']
#
# # 两种方法
# # 方法一:有序字典
# from collections import OrderedDict
# names = list(OrderedDict.fromkeys(names))
# print(names)
#
# # 方法二:利用set
# seen = set()
# names = [x for x in names if not (x in seen or seen.add(x))]
# print(names)
#
"""
#练习十五:
去掉重复,且保证列表顺序与原来保持一致
names=[[1,2],3,[1,2],4]
"""

# 因为字典的key不能是列表,所以这里只能用上面的方法二了。

"""
#练习十六:
统计s='hello alex alex say hello sb sb'中每个单词的个数
"""
# s = 'hello alex alex say hello sb sb'
# s_l = s.split()  # 按空格分割成列表
# keys = set(s_l)  # 取到所有出现过的单词
# for i in keys:
#     print(i, s_l.count(i))  # 打印下数量

"""
#练习十七:字典嵌套使用

Egon老师就是想让你们知道字典可以嵌套,可以用来做事情的。。。
"""


#1、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作





#修改列表中字符串首字母大写



# def file_daxie(file):
#     a=[]
#     for i in file:
#         b=i.capitalize()
#         a.append(b)
#     print(a)
#
#
#
# #2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
#
# def file_num(file):
#     shuzi=zimu=kongge=qita=0
#     for i in file:
#         if i.isdigit():
#             shuzi+=1
#         elif i.isalpha():
#             zimu+=1
#         elif i==' ':
#             kongge+=1
#         else:qita+=1
#     print('数字%s 字母%s  空格%s  其他%s' %(shuzi,zimu,kongge,qita))
#
# #3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
#
# def file_len(file):
#     if len(file)>5:
#         return 1
#     else:
#         return 0
#
# #4、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。
#
# def file_k(file):
#     n=0
#     for i in file:
#         if i==' ':
#             n+=1
#     print('有%s个'%n)
#
#
#
# #5、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
#
# def file_len(file):
#     while len(file)>2:
#         file.pop()
#     print(file)
#
# #6、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
#
# def file_jishu(file):
#     n=len(file);a=[];
#     for i in range(0,n):
#         if i%2==1:
#             a.append(file[i])
#     print(a)
#
#
# #7、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
# dic = {"k1": "v1v1", "k2": [11,22,33,44]}

# #    PS:字典中的value只能是字符串或列表
#
# def file_dic(file):
#     for i in file:
#         if len(file[i])>2:
#             file[i].pop()
#     print(file)



# 一:编写函数,(函数执行的时间是随机的)

# import random
# def t():
#     time.sleep(random.randrange(1,3))
# print('hello')
# # 二:编写装饰器,为函数加上统计时间的功能
#
# import time
# import random
# def timebe(func):
#     def wrapper(*args,**kwargs):
#         start_time=time.time()
#         res = func(*args, **kwargs)
#         end_time=time.time()
#         print('运行时间是:%s' % (end_time - start_time))
#
#         return res
#     return wrapper
#
# @timebe
# def t():
#     time.sleep(random.randrange(2,3))
#     print('hello')
#
#
# # 三:编写装饰器,为函数加上认证的功能
#
# def ident(func):
#     def wrapper(*args,**kwargs):
#         name=input('name:')
#         pwd=input('pwd: ')
#         if name=='zuo' and pwd=='123':
#             print('correct')
#             return func(*args, **kwargs)
#         else:
#             print('wrong')
#     return wrapper
#
#
# @ident
# def t():
#     print('hello')
#
#
#
# # 四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
# #     注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
#
# def iden(func):
#     def wrapper(*args,**kwargs):
#         name=input('name:')
#         pwd=int(input('pwd:'))
#         with open('1.txt','r') as f:
#             a=f.read()
#             a=eval(a)
#             if name in a and pwd==a[name]:
#                 print('corret')
#                 return func(*args,**kwargs)
#             else:
#                 print('error')
#     return wrapper
#
#
# @iden
# def s(x,y):
#     print('sum=%s' %(x+y))
#
#
# @iden
# def mi(a,b):
#     if a>b:
#         print(b)
#     else:
#         print(a)
#
#
#
# # 五:编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
#
# from urllib.request import urlopen
# def index():
#     url='http://cn.bing.com/'
#     def get():
#         return urlopen(url).readlines()
#     return get
# biying=index()
# print(biying())

# 六:为题目五编写装饰器,实现缓存网页内容的功能:
#     具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中
# from urllib.request import urlopen
# import os
# cache_path=r'E:\文本编辑器\pycharm\xiong.txt'
# def make_cache(func):
#     def wrapper(*a,**b):
#        if os.path.getsize(cache_path):
#             print('\033[33m=============>有缓存\033[0m')
#             with open(cache_path,'rb') as f:
#                 res=f.read()
#        else:
#             res=func(*a,**b)
#             with open(cache_path,'wb') as f:
#                 f.write(res)
#        return res
#     return wrapper
# @make_cache
# def get(url):
#     return urlopen(url).read()
# print(get('http://www.onlybrother.com'))
# print(get('http://www.onlybrother.com'))
# print(get('http://www.onlybrother.com'))
# print(get('http://www.onlybrother.com'))


# 七:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,
#
# 完成自动添加到字典的操作
#func_dic={}
# def deco(key):
#     def deco2(func):
#         func_dic[key]=func
#     return deco2
# @deco('f1')
# def f1():
#     print('from f1')
# @deco('f2')
# def f2():
#     print('from f2')
# @deco('f3')
# def f3():
#     print('from f3')
# print(func_dic)
# while True:
#     cmd=input(">>>:").strip()
#     if cmd in func_dic:
#         func_dic[cmd]()




#2 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到文件中
#    注意:时间格式的获取
# import time
# time.strftime('%Y-%m-%d %X')
#
# import time
# def tim(func):
#     def wrapper(*args,**kwargs):
#         print('%s' %time.strftime('%y-%m-%d %X'))
#         return func(*args,**kwargs)
#     return wrapper
#
# #3 判断下列数据类型是可迭代对象or迭代器
#
# s='hello'
# l=[1,2,3,4]
# t=(1,2,3)
# d={'a':1}
# set={1,2,3}
# f=open('a.txt')


#1 编写 tail -f a.txt |grep 'error' |grep '404'命令,周一默写
#复制代码



# import time
#
# def tail(file_path):
#     with open(file_path, encoding='utf-8') as f:
#         f.seek(0,2)
#         while True:
#             line = f.readline()
#             if line:
#                 yield line
#             else:
#                 time.sleep(0.5)
#
# def grep(lines, pattern):
#     for line in lines:
#         if pattern in line:
#             yield line
#
#
# g = grep(grep(tail('te.txt'), 'error'), '404')
# for i in g:
#     print(i)
#
# #复制代码
# l=[1,[2,3,[4,5,[6,7,[8,9,[10,11,[12,13]]]]]]]
# def func(l):
#     for i in l:
#         if isinstance(i,list):
#             func(i)
#         else:
#             print(i)
#
# func(l)


#
#
# #2 文件a.txt内容
# # apple 10 3
# # tesla 100000 1
# # mac 3000 2
# # lenovo 30000 3
# # chicken 10 3
#
# #要求使用列表解析,从文件a.txt中取出每一行,做成下述格式
# [{'name':'apple','price':10,'count':3},{...},{...},...]
#
# #3 格式与2一样,但只保留价格大于1000的商品信息
#
# print([{'name':i.strip().split()[0], 'price':i.strip().split()[1], 'count':i.strip().split()[2]} for i in open('a.txt')])
# print([{'name':i.strip().split()[0], 'price':i.strip().split()[1], 'count':i.strip().split()[2]} for i in open('a.txt') if int(i.strip().split()[1]) > 1000])







#day5_ grep -rl 'python' /root 功能 的实现

# import os
#
# def init(func):
#     def wrapper(*args,**kwargs):
#         res=func(*args,**kwargs)
#         next(res)
#         return res
#     return wrapper
#
# @init
# def search(target):
#     while True:
#         search_path=yield
#         g=os.walk(search_path)
#         for par_dir,_,files in g:
#             for file in files:
#                 file_abs_path=r'%s\%s' %(par_dir,file)
#                 # print(file_abs_path)
#                 target.send(file_abs_path)
#
# @init
# def opener(target):
#     while True:
#         file_abs_path=yield
#         # print('opener func==>',file_abs_path)
#         with open(file_abs_path,encoding='utf-8') as f:
#             target.send((file_abs_path,f))
#
# @init
# def cat(target):
#     while True:
#         file_abs_path,f=yield  #(file_abs_path,f)
#         for line in f:
#             tag=target.send((file_abs_path,line))
#             if tag:
#                 break
# @init
# def grep(target,pattern):
#     tag=False
#     while True:
#         file_abs_path,line=yield tag
#         tag=False
#         if pattern in line:
#             tag=True
#             target.send(file_abs_path)
#
# @init
# def printer():
#     while True:
#         file_abs_path=yield
#         print(file_abs_path)
#
#
#
# x=r'C:\Users\Administrator\PycharmProjects\python17期\day5\a'
#
#
#
# g=search(opener(cat(grep(printer(),'python'))))
# print(g)
#
# g.send(x)



# 1 文件内容如下,标题为:姓名,性别,年纪,薪资
#
# egon male 18 3000
# alex male 38 30000
# wupeiqi female 28 20000
# yuanhao female 28 10000
#
# 要求:
# 从文件中取出每一条记录放入列表中,
# 列表的每个元素都是{'name':'egon','sex':'male','age':18,'salary':3000}的形式
#
# 2 根据1得到的列表,取出薪资最高的人的信息
# 3 根据1到的列表,取出最年轻的人的信息
# 4 根据1得到的列表,将每个人的信息中的名字映射成首字母大写的形式
# 5 根据1得到的列表,过滤掉名字以a开头的人的信息
#

# info_list = [{'name':i.split()[0],'sex':i.split()[1], 'age':i.split()[2], 'salary':i.split()[3]} for i in open('info',encoding='utf-8')]
# print(max(info_list,key=lambda x:x['salary']))     # 最大值
# print(min(info_list,key=lambda x:x['age']))        # 最小值
#
# def func1(x):
#     x['name'] = x['name'].capitalize()
#     return x
# # print(list(map(lambda x:x['name'].capitalize(), info_list)))
# print(list(map(func1, info_list)))
#
#  # 首字母大写,目测有点问题,等会儿解决下
#
#
# print(list(filter(lambda x:not x['name'].startswith('a'), info_list)))
#
#
#
# # 6 使用递归打印j(前两个数的和得到第三个数)
# #     0 1 1 2 3 5 8...
#
#
#
# def nbqe(a=0, b=1):
#     if a < 50000:
#         print(a, end=' ')
#         c = a + b
#         nbqe(b, c)
#
# nbqe()
#
# # =====================================
# l = [0, ]
# def fbnq(a=0, b=1):
#     l[0] = a
#     return b,a+b
#
# a = 0
# b = 1
# total = 100000
# for i in range(total):
#     a, b = fbnq(a, b)
#
# print('第%s个值为:%s'%(total, l[-1]))



# 功能实现:
# 一个文件夹中,存在多个文件,包括图片,视频,文本等等,遍历出时间在2017-06-05至2017-06-09这段时间内创建的所有文件。
#
# # 具体文件夹,自己创建就可以了。
# import os
# import time
# start=time.mktime(time.strptime('2017-06-05','%Y-%m-%d'))
# stop=time.mktime(time.strptime('2017-06-09','%Y-%m-%d'))
#
# # print(os.getcwd())
# # os.chdir(r'D:\dota2')
# # print(os.stat(r'D:\dota2'))
# # for far_fir,sub_dir,files in os.walk(r'D:\dota2'))
# #     for file in files:
# #         file_path='%s\%s'%(far_dir,file)
# #         print(file_path)
# g=os .walk(r'D:\我要')
# for far_dir,sub_dir,files in g:
#     far_dir     #父目录名会把最初的目录名和下属的文件名全部打印出来。
#     d=os.stat(far_dir).st_ctime
#     if d>start and d<stop:
#         print(d)
#     # print(sub_dir)
#     # a=r'%s\%s'%(far_dir,sub_dir)
#     # print(a)
#     # # print(os.stat(a))
#     for file in files:
#         b=r'%s\%s'%(far_dir,file)
#         # print(b,type(b))
#         f=os.stat(b).st_ctime
#         if f > start and f < stop:
#             print(f)
#         # print(os.stat(b))

 

posted on 2017-07-03 23:44  方少0410  阅读(247)  评论(0编辑  收藏  举报