zoukankan      html  css  js  c++  java
  • python16_day02【列表、字典】

    1.列表

      1 names = ['Alex',"Tenglan",'Eric']
      2 
      3 >>> names[0]
      4 'Alex'
      5 >>> names[2]
      6 'Eric'
      7 >>> names[-1]
      8 'Eric'
      9 >>> names[-2] #还可以倒着取
     10 'Tenglan'
     11 
     12 >>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
     13 >>> names[1:4]  #取下标1至下标4之间的数字,包括1,不包括4
     14 ['Tenglan', 'Eric', 'Rain']
     15 >>> names[1:-1] #取下标1至-1的值,不包括-1
     16 ['Tenglan', 'Eric', 'Rain', 'Tom']
     17 >>> names[0:3] 
     18 ['Alex', 'Tenglan', 'Eric']
     19 >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样
     20 ['Alex', 'Tenglan', 'Eric']
     21 >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写
     22 ['Rain', 'Tom', 'Amy'] 
     23 >>> names[3:-1] #这样-1就不会被包含了
     24 ['Rain', 'Tom']
     25 >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个
     26 ['Alex', 'Eric', 'Tom'] 
     27 >>> names[::2] #和上句效果一样
     28 ['Alex', 'Eric', 'Tom']
     29 
     30 
     31 >>> names
     32 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy']
     33 >>> names.append("我是新来的")
     34 >>> names
     35 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
     36 
     37 >>> names
     38 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
     39 >>> names.insert(2,"强行从Eric前面插入")
     40 >>> names
     41 ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
     42 
     43 >>> names.insert(5,"从eric后面插入试试新姿势")
     44 >>> names
     45 ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
     46 
     47 >>> names
     48 ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
     49 >>> names[2] = "该换人了"
     50 >>> names
     51 ['Alex', 'Tenglan', '该换人了', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
     52 删除
     53 
     54 >>> del names[2] 
     55 >>> names
     56 ['Alex', 'Tenglan', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
     57 >>> del names[4]
     58 >>> names
     59 ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
     60 >>> 
     61 >>> names.remove("Eric") #删除指定元素
     62 >>> names
     63 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', '我是新来的']
     64 >>> names.pop() #删除列表最后一个值 
     65 '我是新来的'
     66 >>> names
     67 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
     68 
     69 >>> names
     70 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
     71 >>> b = [1,2,3]
     72 >>> names.extend(b)
     73 >>> names
     74 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
     75 
     76 >>> names
     77 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
     78 
     79 >>> name_copy = names.copy()
     80 >>> name_copy
     81 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
     82 
     83 >>> names
     84 ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]
     85 >>> names.count("Amy")
     86 2
     87 
     88 
     89 >>> names
     90 ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]
     91 >>> names.sort() #排序
     92 Traceback (most recent call last):
     93   File "<stdin>", line 1, in <module>
     94 TypeError: unorderable types: int() < str()   #3.0里不同数据类型不能放在一起排序了,擦
     95 >>> names[-3] = '1'
     96 >>> names[-2] = '2'
     97 >>> names[-1] = '3'
     98 >>> names
     99 ['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '1', '2', '3']
    100 >>> names.sort()
    101 >>> names
    102 ['1', '2', '3', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom']
    103 
    104 >>> names.reverse() #反转
    105 >>> names
    106 ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']
    107 
    108 >>> names
    109 ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']
    110 >>> names.index("Amy")
    111 2 #只返回找到的第一个下标
    View Code

    2.元组

    names = ("alex","jack","eric")
    它只有2个方法,一个是count,一个是index

    3.字符串

     1 name.capitalize()  首字母大写
     2 name.casefold()   大写全部变小写
     3 name.center(50,"-")  输出 '---------------------Alex Li----------------------'
     4 name.count('lex') 统计 lex出现次数
     5 name.encode()  将字符串编码成bytes格式
     6 name.endswith("Li")  判断字符串是否以 Li结尾
     7  "Alex	Li".expandtabs(10) 输出'Alex      Li', 将	转换成多长的空格 
     8  name.find('A')  查找A,找到返回其索引, 找不到返回-1 
     9 
    10 format :
    11     >>> msg = "my name is {}, and age is {}"
    12     >>> msg.format("alex",22)
    13     'my name is alex, and age is 22'
    14     >>> msg = "my name is {1}, and age is {0}"
    15     >>> msg.format("alex",22)
    16     'my name is 22, and age is alex'
    17     >>> msg = "my name is {name}, and age is {age}"
    18     >>> msg.format(age=22,name="ale")
    19     'my name is ale, and age is 22'
    20 format_map
    21     >>> msg.format_map({'name':'alex','age':22})
    22     'my name is alex, and age is 22'
    23 
    24 
    25 msg.index('a')  返回a所在字符串的索引
    26 '9aA'.isalnum()   True
    27 
    28 '9'.isdigit() 是否整数
    29 name.isnumeric  
    30 name.isprintable
    31 name.isspace
    32 name.istitle
    33 name.isupper
    34  "|".join(['alex','jack','rain'])
    35 'alex|jack|rain'
    36 
    37 
    38 maketrans
    39     >>> intab = "aeiou"  #This is the string having actual characters. 
    40     >>> outtab = "12345" #This is the string having corresponding mapping character
    41     >>> trantab = str.maketrans(intab, outtab)
    42     >>> 
    43     >>> str = "this is string example....wow!!!"
    44     >>> str.translate(trantab)
    45     'th3s 3s str3ng 2x1mpl2....w4w!!!'
    46 
    47  msg.partition('is')   输出 ('my name ', 'is', ' {name}, and age is {age}') 
    48 
    49  >>> "alex li, chinese name is lijie".replace("li","LI",1)
    50      'alex LI, chinese name is lijie'
    51 
    52  msg.swapcase 大小写互换
    53 
    54 
    55  >>> msg.zfill(40)
    56 '00000my name is {name}, and age is {age}'
    57 
    58 
    59 
    60 >>> n4.ljust(40,"-")
    61 'Hello 2orld-----------------------------'
    62 >>> n4.rjust(40,"-")
    63 '-----------------------------Hello 2orld'
    64 
    65 
    66 >>> b="ddefdsdff_哈哈" 
    67 >>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则
    68 True
    View Code

    4.字典

    • dict是无序的
    • key必须是唯一的,so 天生去重
    info = {
        'stu1101': "TengLan Wu",
        'stu1102': "LongZe Luola",
        'stu1103': "XiaoZe Maliya",
    }

      增加

    1 >>> info["stu1104"] = "苍井空"
    2 >>> info
    3 {'stu1102': 'LongZe Luola', 'stu1104': '苍井空', 'stu1103': 'XiaoZe Maliya', 'stu1101': 'TengLan Wu'}
    View Code

      修改

    1 >>> info['stu1101'] = "武藤兰"
    2 >>> info
    3 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}
    4 删除
    View Code

      删除

     1 >>> info
     2 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}
     3 >>> info.pop("stu1101") #标准删除姿势
     4 '武藤兰'
     5 >>> info
     6 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
     7 >>> del info['stu1103'] #换个姿势删除
     8 >>> info
     9 {'stu1102': 'LongZe Luola'}
    10 >>> 
    11 >>> 
    12 >>> 
    13 >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
    14 >>> info
    15 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #随机删除
    16 >>> info.popitem()
    17 ('stu1102', 'LongZe Luola')
    18 >>> info
    19 {'stu1103': 'XiaoZe Maliya'}
    View Code

      查找

     1 >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
     2 >>> 
     3 >>> "stu1102" in info #标准用法
     4 True
     5 >>> info.get("stu1102")  #获取
     6 'LongZe Luola'
     7 >>> info["stu1102"] #同上,但是看下面
     8 'LongZe Luola'
     9 >>> info["stu1105"]  #如果一个key不存在,就报错,get不会,不存在只返回None
    10 Traceback (most recent call last):
    11   File "<stdin>", line 1, in <module>
    12 KeyError: 'stu1105'
    View Code

      嵌套

     1 av_catalog = {
     2     "欧美":{
     3         "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
     4         "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
     5         "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
     6         "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
     7     },
     8     "日韩":{
     9         "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
    10     },
    11     "大陆":{
    12         "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
    13     }
    14 }
    15 
    16 av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来"
    17 print(av_catalog["大陆"]["1024"])
    18 #ouput 
    19 ['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']
    View Code

      方法

     1 #values
     2 >>> info.values()
     3 dict_values(['LongZe Luola', 'XiaoZe Maliya'])
     4 
     5 #keys
     6 >>> info.keys()
     7 dict_keys(['stu1102', 'stu1103'])
     8 
     9 
    10 #setdefault
    11 >>> info.setdefault("stu1106","Alex")
    12 'Alex'
    13 >>> info
    14 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
    15 >>> info.setdefault("stu1102","龙泽萝拉")
    16 'LongZe Luola'
    17 >>> info
    18 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
    19 
    20 
    21 #update 
    22 >>> info
    23 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
    24 >>> b = {1:2,3:4, "stu1102":"龙泽萝拉"}
    25 >>> info.update(b)
    26 >>> info
    27 {'stu1102': '龙泽萝拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
    28 
    29 #items
    30 info.items()
    31 dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')])
    32 
    33 
    34 #通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个
    35 >>> dict.fromkeys([1,2,3],'testd')
    36 {1: 'testd', 2: 'testd', 3: 'testd'}
    View Code

      循环两个方法

    1 #方法1【高效】
    2 for key in info:
    3     print(key,info[key])
    4 
    5 #方法2
    6 for k,v in info.items(): #会先把dict转成list,数据里大时莫用
    7     print(k,v)
    View Code

    5.集合

    集合是一个无序的,不重复的数据组合,它的主要作用如下:

    • 去重,把一个列表变成集合,就自动去重了
    • 关系测试,测试两组数据之前的交集、差集、并集等关系
     1 s = set([3,5,9,10])      #创建一个数值集合  
     2   
     3 t = set("Hello")         #创建一个唯一字符的集合  
     4 
     5 
     6 a = t | s          # t 和 s的并集  
     7   
     8 b = t & s          # t 和 s的交集  
     9   
    10 c = t – s          # 求差集(项在t中,但不在s中)  
    11   
    12 d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中)  
    13   
    14    
    15   
    16 基本操作:  
    17   
    18 t.add('x')            # 添加一项  
    19   
    20 s.update([10,37,42])  # 在s中添加多项  
    21   
    22    
    23   
    24 使用remove()可以删除一项:  
    25   
    26 t.remove('H')  
    27   
    28   
    29 len(s)  
    30 set 的长度  
    31   
    32 x in s  
    33 测试 x 是否是 s 的成员  
    34   
    35 x not in s  
    36 测试 x 是否不是 s 的成员  
    37   
    38 s.issubset(t)  
    39 s <= t  
    40 测试是否 s 中的每一个元素都在 t 中  
    41   
    42 s.issuperset(t)  
    43 s >= t  
    44 测试是否 t 中的每一个元素都在 s 中  
    45   
    46 s.union(t)  
    47 s | t  
    48 返回一个新的 set 包含 s 和 t 中的每一个元素  
    49   
    50 s.intersection(t)  
    51 s & t  
    52 返回一个新的 set 包含 s 和 t 中的公共元素  
    53   
    54 s.difference(t)  
    55 s - t  
    56 返回一个新的 set 包含 s 中有但是 t 中没有的元素  
    57   
    58 s.symmetric_difference(t)  
    59 s ^ t  
    60 返回一个新的 set 包含 s 和 t 中不重复的元素  
    61   
    62 s.copy()  
    63 返回 set “s”的一个浅复制
    View Code

    6.文件操作

    1. 打开文件,得到文件句柄并赋值给一个变量
    2. 通过句柄对文件进行操作
    3. 关闭文件 
    1 f = open('lyrics') #打开文件
    2 first_line = f.readline()
    3 print('first line:',first_line) #读一行
    4 print('我是分隔线'.center(50,'-'))
    5 data = f.read()# 读取剩下的所有内容,文件大时不要用
    6 print(data) #打印文件
    7  
    8 f.close() #关闭文件
    View Code
     1 打开文件的模式有:
     2 
     3 r,只读模式(默认)。
     4 w,只写模式。【不可读;不存在则创建;存在则删除内容;】
     5 a,追加模式。【可读;   不存在则创建;存在则只追加内容;】
     6 "+" 表示可以同时读写某个文件
     7 
     8 r+,可读写文件。【可读;可写;可追加】
     9 w+,写读
    10 a+,同a
    11 "U"表示在读取时,可以将 
     
     
    自动转换成 
     (与 r 或 r+ 模式同使用)
    12 
    13 rU
    14 r+U
    15 "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
    16 
    17 rb
    18 wb
    19 ab
    with open('log','r') as f:

    6.作业

       程序1: 实现简单的shell sed替换功能

     1 #!/usr/bin/env python3
     2 # -*-coding:utf8-*-
     3 # __author__ = "willian"
     4 
     5 import os
     6 import sys
     7 
     8 def main():
     9     """this is main def."""
    10     arg = sys.argv[1:]
    11     arg_len = len(arg)
    12     if arg_len != 3:
    13         print("33[31;1m需要3个参数,你只给{0}个({1} old_string new_string file.txt)33[0m".format(arg_len, sys.argv[0]))
    14         exit()
    15     else:
    16         if os.path.exists(sys.argv[-1]):
    17             f1 = open(sys.argv[-1], 'r+')
    18             f2 = open("{0}.temp".format(sys.argv[3]), 'w')
    19             for line in f1:
    20                 line = line.replace(sys.argv[1], sys.argv[2])
    21                 f2.write(line)
    22                 f2.flush()
    23             f1.close()
    24             f2.close()
    25 
    26             f1_size = os.path.getsize(sys.argv[-1])
    27             f2_size = os.path.getsize("{0}.temp".format(sys.argv[-1]))
    28             if f1_size == f2_size:
    29                 os.remove(sys.argv[-1])
    30                 os.renames("{0}.temp".format(sys.argv[-1]), sys.argv[-1])
    31             else:
    32                 print("33[31;1m文件替换出错!33[0m")
    33                 exit()
    34         else:
    35             print("33[31;1m[{0}]33[0m文件不存在.".format(sys.argv[-1]))
    36 
    37 if __name__ == '__main__':
    38     main()
    View Code

       程序2: 三级菜单

      1 #!/usr/bin/env python
      2 # -*-coding:utf8-*-
      3 # __author__ = "willian"
      4 
      5 menu = {
      6     '北京': {'海淀': {'五道口': {'soho': {},
      7                                 '网易': {},
      8                                 'google': {},
      9                                 },
     10                     '中关村': {'爱奇艺': {},
     11                                 '汽车之家': {},
     12                                 'youku': {}, },
     13                     },
     14 
     15             '昌平': {'沙河':   {'老男孩': {},
     16                                 '北航': {},
     17                                 '包子': {}, },
     18                     '天通苑': {'1区': {},
     19                               "2区": {},
     20                               "3区": {}},
     21                    },
     22            },
     23 
     24     "上海": {'普陀': {"东区": {'vipabc': {},
     25                             '永久自行车': {},
     26                             '老上海': {}},
     27                      "西区": {"东方明珠": {},
     28                                 '上海滩': {},
     29                                 "陆家嘴": {}}
     30                             },
     31            "浦东": {"南城": {"浦发银行": {},
     32                             "桥水": {},
     33                             "招商银行": {},
     34                            },
     35                     "北城": {"虹桥机场": {},
     36                           "火车站": {},
     37                           "自贸区": {}
     38                            }
     39                  }
     40            },
     41 
     42     "天津": {'滨海区': {"东区": {'天津港口': {},
     43                             '天津自行车': {},
     44                             '老天津人': {}},
     45                      "西区": {"东方天津": {},
     46                                 '天津滩': {},
     47                                 "陆家天津": {}}
     48                             },
     49            "武清": {"南城": {"天津银行": {},
     50                             "桥水天津": {},
     51                             "天津很行": {},
     52                            },
     53                     "北城": {"天津机场": {},
     54                           "天津火车站": {},
     55                           "天津自贸区": {}
     56                            }
     57                  }
     58            },
     59         "南京": {'玄武': {"东区": {'大屠杀': {},
     60                             '28自行车': {},
     61                             '老人': {}},
     62                      "西区": {"老人与海": {},
     63                                 '什么': {},
     64                                 "苦口良": {}}
     65                             },
     66            "江宁": {"南城": {"东陈轼": {},
     67                             "无所谓": {},
     68                             "南京银行": {},
     69                            },
     70                     "北城": {"南京机场": {},
     71                           "南京火车站": {},
     72                           "南京自贸区": {}
     73                            }
     74                  }
     75            }
     76     }
     77 
     78 
     79 def main():
     80     """**this is main line!**"""
     81 
     82     while True:
     83         L1 = []
     84         # 第一层的数据加入到L1列表. L1 = ['上海', '北京']
     85         for key in menu.keys():
     86             L1.append(key)
     87         # show L1数据
     88         for show_index, show_L1 in enumerate(L1, 1):
     89             print(show_index, show_L1)
     90         # 处理空值
     91         choice1 = input("33[32;1m>33[0m请选择城市[按'b'反回上一级,按'q'则退出]:").strip()
     92         if len(choice1) == 0:
     93             continue
     94         # 主线
     95         else:
     96             # 主线判断输入是数据
     97             if choice1.isdigit():
     98                 # 转成INT
     99                 choice1 = int(choice1)
    100                 if choice1-1 < len(L1):
    101                     get_city = L1[choice1-1]
    102                     while True:
    103                         # 主线第二层
    104                         L2 = []
    105                         menu2 = menu[get_city]
    106                         for key in menu2.keys():
    107                             L2.append(key)
    108                         for show_index2, show_L2 in enumerate(L2, 1):
    109                             print(show_index2, show_L2)
    110                         choice2 = input("33[32;1m>>33[0m请告诉地区[按'b'反回上一级,按'q'则退出]:")
    111                         if len(choice2) == 0:
    112                             continue
    113                         else:
    114                             if choice2.isdigit():
    115                                 # 转成INT
    116                                 choice2 = int(choice2)
    117                                 if choice2-1 < len(L2):
    118                                     get_area = L2[choice2-1]
    119                                     while True:
    120                                         # 主线第三层
    121                                         L3 = []
    122                                         menu3 = menu2[get_area]
    123                                         for key in menu3.keys():
    124                                             L3.append(key)
    125                                         for show_index3, show_L3 in enumerate(L3, 1):
    126                                             print(show_index3, show_L3)
    127                                         choice3 = input("33[32;1m>>>33[0m请告诉县城[按'b'反回上一级,按'q'则退出]:")
    128                                         if len(choice3) == 0:
    129                                             continue
    130                                         else:
    131                                             if choice3.isdigit():
    132                                                 # 转换INT
    133                                                 choice3 = int(choice3)
    134                                                 if choice3-1 < len(L3):
    135                                                     get_place = L3[choice3-1]
    136                                                     while True:
    137                                                         # end
    138                                                         menu4 = menu3[get_place]
    139                                                         for i in menu4:
    140                                                             print("33[33;1m{0}33[0m".format(i))
    141 
    142                                                         end = input("[按'b'反回上一级,按'q'则退出]").strip()
    143                                                         if len(end) == 0:
    144                                                             continue
    145                                                         else:
    146                                                             if end == 'b':
    147                                                                 break
    148                                                             elif end == 'q':
    149                                                                 exit()
    150                                                             else:
    151                                                                 print("33[31;1m不懂你的输入[按'b'反回上一级,按'q'则退出]!33[0m")
    152                                                                 continue
    153                                                 else:
    154                                                     print("33[31;1m超出范围!33[0m")
    155                                                     continue
    156                                             else:
    157                                                 if choice3 == 'b':
    158                                                     break
    159                                                 elif choice3 == 'q' or choice3 == 'Q':
    160                                                     exit()
    161                                                 else:
    162                                                     print("33[31;1m不懂你的输入[按'b'反回上一级,按'q'则退出]!33[0m")
    163                                                     continue
    164                                 else:
    165                                     print("33[31;1m超出范围!33[0m")
    166                                     continue
    167                             else:
    168                                 if choice2 == 'b':
    169                                     break
    170                                 elif choice2 == 'q' or choice2 == 'Q':
    171                                     exit()
    172                                 else:
    173                                     print("33[31;1m不懂你的输入[按'b'反回上一级,按'q'则退出]!33[0m")
    174                                     continue
    175                 else:
    176                     print("33[31;1m超出范围[按'b'反回上一级,按'q'则退出]!33[0m")
    177                     continue
    178 
    179             # 处理b,q和其它乱七八槽.
    180             else:
    181                 if choice1 == 'b':
    182                     print("33[31;1m不能再返回了,按q退出!33[0m")
    183                     continue
    184                 elif choice1 == 'q' or choice1 == 'Q':
    185                     exit()
    186                 else:
    187                     print("33[31;1m不懂你的输入[按'b'反回上一级,按'q'则退出]!33[0m")
    188                     continue
    189 
    190 if __name__ == '__main__':
    191     main()
    View Code
     1 #!/usr/bin/env python
     2 # -*-coding:utf8-*-
     3 # __author__ = "willian"
     4 
     5 
     6 menu = {
     7     '北京':{
     8         '海淀':{
     9             '五道口':{
    10                 'soho':{},
    11                 '网易':{},
    12                 'google':{}
    13             },
    14             '中关村':{
    15                 '爱奇艺':{},
    16                 '汽车之家':{},
    17                 'youku':{},
    18             },
    19             '上地':{
    20                 '百度':{},
    21             },
    22         },
    23         '昌平':{
    24             '沙河':{
    25                 '老男孩':{},
    26                 '北航':{},
    27             },
    28             '天通苑':{},
    29             '回龙观':{},
    30         },
    31         '朝阳':{},
    32         '东城':{},
    33     },
    34     '上海':{
    35         '闵行':{
    36             "人民广场":{
    37                 '炸鸡店':{}
    38             }
    39         },
    40         '闸北':{
    41             '火车战':{
    42                 '携程':{}
    43             }
    44         },
    45         '浦东':{},
    46     },
    47     '山东':{},
    48 }
    49 
    50 
    51 current_layer = menu
    52 p_layer = []
    53 
    54 while True:
    55     for k in current_layer:
    56         print(k)
    57     choice = input(">:").strip()
    58     if len(choice) == 0:
    59         continue
    60     if choice in current_layer:
    61         p_layer.append(current_layer)
    62         current_layer = current_layer[choice]
    63     elif choice == 'b':
    64         if len(p_layer) > 0:
    65             current_layer = p_layer.pop()
    66     elif choice == 'q':
    67         exit('bye')
    View Code

      程序3: 购物

     1 #!/usr/bin/env python
     2 # coding:utf8
     3 __author__ = "willian"
     4 
     5 # dictionary
     6 shop_list = [
     7     ['iphone', 6500],
     8     ['mac', 12000],
     9     ['office', 30],
    10 ]
    11 
    12 print(len(shop_list))
    13 # variables
    14 salary = int(input("请输入你的收入:"))
    15 car = []
    16 total = 0
    17 
    18 # print list
    19 for k, v in enumerate(shop_list, 1):
    20     print(k, v[0], v[1])
    21 
    22 while True:
    23     choice = input("你想买点什么?")
    24     print(salary)
    25     if choice.isalpha():
    26         if choice == 'exit' or 'quit':
    27             for i in car:
    28                 print("你购买了:33[32;1m{0},{1}33[0m".format(i[0], i[1]))
    29                 total += i[1]
    30             print("total:33[31;1m{0}33[0m".format(total))
    31             exit()
    32         else:
    33             continue
    34 
    35     elif choice.isdigit:
    36         if int(choice) < len(shop_list):
    37             ret = shop_list[int(choice)-1]
    38             if salary > ret[1]:
    39                 salary = salary - ret[1]
    40                 print("您消费了:33[31;1m{0}33[0m".format(ret[1]))
    41                 car.append(ret)
    42             else:
    43                 print("你的钱不够,还差33[31;0m{0}33[0m".format(ret[1] - salary))
    44 
    45         else:
    46             print("33[31;1m没有些商品.33[0m")
    47             continue
    View Code
  • 相关阅读:
    自然数幂和的若干种解法
    线性预处理逆元
    差分与有限微积分
    UVALive 6859——凸包&&周长
    UVALive 6858——分类讨论&&水题
    UVALive 6862——结论题&&水题
    ZOJ4019——贪心&&DP
    [LeetCode] Power of Two
    循环队列实现(C++) Ring Buffer
    正确使用stl vecotr erase函数
  • 原文地址:https://www.cnblogs.com/weibiao/p/6291138.html
Copyright © 2011-2022 走看看