今天跟了Alex老师学了一些Python 的知识,觉得受益匪浅。今天也要把自己学习之路记录下来。自己往后遇到什么基础问题时也能自己回来这个找相关的内容。的确是个好方法。

本节内容

  1. 列表、元组操作
  2. 字符串操作
  3. 字典操作
  4. 集合操作
  5. 文件操作
  6. 字符编码与转码 

 

1.列表、元组操作

#列表的用法
names=["Judy","John","Leo","Tom"]

#寻址:取单个元素
print(names[0])
print(names[1])
print(names[-1])

#切片:取多个元素
print(names[1:3])  #切片,取数为下标1-3之间的数,顾头不顾尾,即取值下标为1,2的数
print(names[:-1])  #切片,不填即为0位开始,所以就是首位到尾位,不包括尾位。
print(names[::2])  #从下标0开始,各位输出

#追加
names.append( "Cooki") #在列表追加一个元素
print(names)

#插入
names.insert(1,"Chak") #在下标1的位置插入"chak"的名字
print(names)

#修改
names[2]="Judy"
print(names)

#删除
#del names    #删除整个列表
del names[2#把列表中的下标为2的元素删除
names.pop(2#把列表中的下标为2的元素删除 **常用方法
names.remove("Cooki")    #把列表中的"Cooki"元素删除
print(names)

#扩展
b=["Tomi","Tony","Terence","Cooki"]
names.extend(b)        
#把另外一个列表的元素加进列表里
print(names)

#拷贝
'''
names2=[]
names2=names.copy()    #
该拷贝为浅拷贝
print(names2)
print("-----------------------------------------")
#names.append(["1","2","3"])
names2=names.copy()
names[-1][0]="5"
print(names)
print(names2)
'''

#统计:计数
print(names.count("Judy"))   #统计列表中元素"Judy"有多少个

#排序、翻转
names.sort()        #在py3.0以上,不能str()/list()  str/int() 的排序
print(names)

#获取下标
names.index("Judy")
print(names.index("Judy"))     #获取下标

 

2.字符串的操作

name.capitalize()  首字母大写

name.casefold()   大写全部变小写

name.center(50,"-"输出 '---------------------Alex Li----------------------'

name.count('lex') 统计 lex出现次数

name.encode()  将字符串编码成bytes格式

name.endswith("Li"判断字符串是否以 Li结尾

 

 

 

 

 

name= "john"

msg ="my name is {}, and age is {}"
print(msg.format(name,22))                           #format 的使用方法 1

msg ="          my name is {name}     , and age is {age}           "     #format 的使用方法 2
print(msg.format(name=name,age=22))

print(msg.index("e"))          #返回e所在的字符串索引

print( "1".isalnum() )         #判断是否为数字

print(msg.isdigit())           #判断是否为整数

print(msg.encode().decode())            #把字符串转换成二进制,encode 字符串转二进制,decode 二进制转字符串


print(msg.partition("s"))          # 用s作为划分成分段的字符串
print(msg.zfill(70))               # 自动用0补全到70个字符串
print(msg.strip() )                # 去头去尾部的空格

 

3.字典

info = {

    'stu1101': "TengLan Wu",                    #{’key’,”value”}

    'stu1102': "LongZe Luola",

    'stu1103': "XiaoZe Maliya",

}

字典的特性:

  • dict是无序的
  • key必须是唯一的,so 天生去重,必须通过 key 去寻找我们想要的value
    • #字典的增加
      info["stu1104"] = "xuxu"
      print(info)

      #字典的修改
      info['stu1101'] = "Judy"
      print(info)

      #字典的删除
      #info.clear()             #把字典的全部内容都删除了
      #info.pop("stu1104")     #把字典中key为stu1104的元素删除  常用方式
      #del info["stu1103"]    #把字典中key为stu1103的元素删除
      #info.popitem()          #把字典中随意删除一个元素
      print(info)

      #字典的查找
      print("stu1104" in info)    #查找的标准用法

      info.get("stu1103")
      print(info.get("stu1103"))     #自己通过key获取value
      print(info.get("stu1105"))     #如果一个key不存在,就报错,get不会,不存在只返回None


      #多级字典嵌套及操作
      '''
      av_catalog = {
          "
      欧美":{
              "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
              "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
              "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
              "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
          },
          "日韩":{
              "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
          },
          "大陆":{
              "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
          }
      }

      av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来"
      print(av_catalog["大陆"]["1024"])
      '''
      #字典一些其他用法
      print(info.values())           #直接输出info中的value的值
      print(info.keys())             #直接输出info中的key的值

      info.setdefault("stu1106","john")      #在字典中设置默认值,若字典里不相应的key,则生产,若有对应的key,命令无反应
      print(info)
      info.setdefault(
      "stu1104","aaaa")
      print(info)
      '''
      b = {1:2,3:4,"stu1104":"aaa"}           #
      从新的字典引入元素,若本字典没有则添加,若本字典有则做出变更
      info.update(b)
      print(info)
      '''

      info.items()
      print(info.items())                    #把字典转成列表

      #字典的循环
      #方法1
      for key in info:                       #最好的方法
         
      print(key,info[key])
      #方法2
      for key,value in info.items():          #会先把dict转成list,数据里大时莫用
         
      print(key,value)

 

程序:购物车程序

需求:

  1. 1.   启动程序后,让用户输入工资,然后打印商品列表
  2. 2.   允许用户根据商品编号购买商品
  3. 3.   用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 4.   可随时退出,退出时,打印已购买商品和余额

 

product_list = [
    (
'Iphone',5800),
    (
'Mac Pro',9800),
    (
'Bike',800),
    (
'Watch',10600),
    (
'Coffee',31),
    (
'Alex Python',120),
]
shop_list = []
user_money =
input("请输入你的共有多少钱:")
if user_money.isdigit():
    salary =
int(user_money)
   
while True:
       
for index, item in enumerate(product_list):
           
print(index, item)
        user_buy =
input("你想买哪个商品,请输入编号:")
       
if user_buy.isdigit():
            user_buy =
int(user_buy)
           
if user_buy < 6 and user_buy >= 0:
               
if user_money > product_list[user_buy][1]:
                    shop_list.append(product_list[user_buy])
                    user_money -= product_list[user_buy][
1]
                   
print("你买了%s,还生下\033[31;1m%sRMB\033[0m" % (shop_list, user_money))
               
else:
                   
print("\033[91;1m不够钱,快回去赚钱\033[0m")

           
else:
               
print("输入有误,请重新输入")
               
continue
        elif
user_buy == "q":
           
for i in shop_list:
               
if i == 0:
                   
print("你啥都没买,皮一下是不是很开心")
               
print("你一共买了这些商品", i)
           
print("\033[41;1m你最后剩下多少%sRMB\033[0m" % user_money)
           
exit()
       
else:
           
print("invalid option")


程序: 三级菜单

要求

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

 

data = {
   
'北京':{
       
"昌平":{
           
"沙河":["oldboy","test"],
           
"天通苑":["链家地产","我爱我家"]
        },
       
"朝阳":{
           
"望京":["奔驰","陌陌"],
           
"国贸":{"CICC","HP"},
           
"东直门":{"Advent","飞信"},
        },
       
"海淀":{},
    },
   
'山东':{
       
"德州":{},
       
"青岛":{},
       
"济南":{}
    },
   
'广东':{
       
"东莞":{},
       
"常熟":{},
       
"佛山":{},
    },
}
exit_flag =
False

while not
exit_flag:
   
for i in data:
       
print(i)
    choice =
input("选择进入1>>:")
   
if choice in data:
       
while not exit_flag:
           
for i2 in data[choice]:
               
print("\t",i2)
            choice2 =
input("选择进入2>>:")
           
if choice2 in data[choice]:
               
while not exit_flag:
                   
for i3 in data[choice][choice2]:
                       
print("\t\t", i3)
                    choice3 =
input("选择进入3>>:")
                   
if choice3 in data[choice][choice2]:
                       
for i4 in data[choice][choice2][choice3]:
                           
print("\t\t",i4)
                        choice4 =
input("最后一层,按b返回>>:")
                       
if choice4 == "b":
                           
pass
                        elif
choice4 == "q":
                            exit_flag =
True
                    if
choice3 == "b":
                       
break
                    elif
choice3 == "q":
                        exit_flag =
True
            if
choice2 == "b":
               
break
            elif
choice2 == "q":
                exit_flag =
True

 

 

 

 

另外简约的方法

menu = {

    '北京':{

        '海淀':{

            '五道口':{

                'soho':{},

                '网易':{},

                'google':{}

            },

            '中关村':{

                '爱奇艺':{},

                '汽车之家':{},

                'youku':{},

            },

            '上地':{

                '百度':{},

            },

        },

        '昌平':{

            '沙河':{

                '老男孩':{},

                '北航':{},

            },

            '天通苑':{},

            '回龙观':{},

        },

        '朝阳':{},

        '东城':{},

    },

    '上海':{

        '闵行':{

            "人民广场":{

                '炸鸡店':{}

            }

        },

        '闸北':{

            '火车战':{

                '携程':{}

            }

        },

        '浦东':{},

    },

    '山东':{},

}

 

 

exit_flag = False

current_layer = menu

 

layers = [menu]

 

whilenot  exit_flag:

    for k in current_layer:

        print(k)

    choice = input(">>:").strip()

    if choice == "b":

        current_layer = layers[-1]

        #print("change to laster", current_layer)

        layers.pop()

    elif choice not  in current_layer:continue

    else:

        layers.append(current_layer)

        current_layer = current_layer[choice]

 

 

最后附上Alex老师博客的链接

http://www.cnblogs.com/alex3714/articles/5717620.html