python基础,python第二课

python基础第二天的课程,主要内容列表,元祖,字典,字符串等主要内容

列表

定义列表 

>>> names = ["ZhangSan","LiSi","WangWu","ZhaoLiu",["ZhangXin","MengDong"],"ZongQi","HeiBa","DongJiu"]
>>> print(names)
['ZhangSan', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa', 'DongJiu']

列表取值

>>> names[0]   #names列表元素从左往右,从0开始数
'ZhangSan'
>>> names[4][0]
'ZhangXin'

列表切片

>>> print(names[0])
ZhangSan
>>> print(names[0:])     #从第一个元素取到最末
['ZhangSan', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa', 'DongJiu']
>>> print(names[-1])    #取最后一个元素
DongJiu
>>> print(names[:-1])    #从第一个元素取到最后一个(不包含最后一个)
['ZhangSan', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa']
>>> print(names[-2:])    #取最后两个元素
['HeiBa', 'DongJiu']
>>> print(names[:4])     #取前4个元素
['ZhangSan', 'LiSi', 'WangWu', 'ZhaoLiu']
>>> print(names[-4:])    #取后四个元素
[['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa', 'DongJiu']
>>> print(names[::2])    #从头开始取,2代表,每隔一个取一个。 如果是3,每两个取一个,以此类推
['ZhangSan', 'WangWu', ['ZhangXin', 'MengDong'], 'HeiBa']

列表的操作

>>> names.append("DaWa") #在列表内最后追加
>>> print(names)
['ZhangSan', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa', 'DongJiu', 'DaWa']
names.insert(1,"ErWa")  #在下标位置为1的元素前插入
>>> print(names)
['ZhangSan', 'ErWa', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa', 'DongJiu', 'DaWa']
>>> names[1]="SanWa"
>>> print(names)
['ZhangSan', 'SanWa', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa', 'DongJiu', 'DaWa']
>>> del names[0]    #删除元素下标位置的数据
>>> print(names)
['SanWa', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa', 'DongJiu', 'DaWa']
>>> names.remove("DaWa")   #删除指定数据
>>> print(names)
['SanWa', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa', 'DongJiu']
>>> names.pop()      #删除最后一个数据
'DongJiu'
>>> print(names)
['SanWa', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa']
>>> print(names)
['SanWa', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa']
>>> names2=["1","2","3","4","5","6","LiSi"]
>>> names.extend(names2)       #在names列表数据后面追加names2的数据
>>> print(names)
['SanWa', 'LiSi', 'WangWu', 'ZhaoLiu', ['ZhangXin', 'MengDong'], 'ZongQi', 'HeiBa', '1', '2', '3', '4', '5', '6', 'LiSi']
>>> names1 = ['one','two','three','four',["five","six"],7,8,9,]
>>> names2 = names1.copy()
>>> print(names2)
['one', 'two', 'three', 'four', ['five', 'six'], 7, 8, 9]
>>> names2[4][1]= "none"   #修改name2列表中的列表数据后,names1中的值也跟着修改
>>> print(names1)  
['one', 'two', 'three', 'four', ['five', 'none'], 7, 8, 9]
>>> print(names2)
['one', 'two', 'three', 'four', ['five', 'none'], 7, 8, 9]
>>> names=["LiSi","1","2","3","4","5","6","LiSi"]
>>> names.count("LiSi")
2
>>> names = ['one','two','three','four',"7","8","9"]
>>> names.sort()
>>> print(names) #按ASCII编码排序
['7', '8', '9', 'four', 'one', 'three', 'two']
>>> names = ['one','two','three','four',"7","8","9"]
>>> names.reverse()
>>> print(names)
['9', '8', '7', 'four', 'three', 'two', 'one']
>>> names
['9', '8', '7', 'four', 'three', 'two', 'one']
>>> names.index("four")  #获取该元素下标值
3

元组

元组tuple和列表十分类似,只不过元组和字符串一样是不可变的,即你不能修改元组。

定义元组

>>> t_name = ("zhang","li","wang","zhao","sun")
>>> print(t_name)
('zhang', 'li', 'wang', 'zhao', 'sun')

 元组操作

统计

>>> t_name = ("zhang","li","wang","zhao","sun")
>>> t_name.count("sun")
1

获取下标

>>> t_name.index("wang")
2

购物车练习

  • 启动程序后,让用户输入工资,然后打印商品列表
  • 允许用户根据商品编号购买商品
  • 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  • 可随时退出,退出时,打印已购买商品和余额
 1 shoping_list = [
 2     ('iphone',5800),
 3     ('Mac Pro', 16000),
 4     ("bike", 800),
 5     ("python book", 58),
 6 ]
 7 curt_list = []          #购物车列表
 8 salary = input("你的工资是多少:")
 9 if salary.isdigit():    #判断是否是整数
10     salary = int(salary)  #转整型
11     while True:
12         for index,item in enumerate(shoping_list):  #循环打印商品列表
13 #            print(shoping_list.index(item),item)
14             print(index,item)         
15         choice_number = input("请输入你要选择的编号:")
16         if choice_number.isdigit():          
17             choice_number = int(choice_number)
18             if choice_number  < len(shoping_list)  and  choice_number >=0:    #判断选择编号是否存在
19                 p_item = shoping_list[choice_number]                  #选择商品
20                 if p_item[1] <= salary:                         #判断 商品价格小于等于工资 购买,否则提示余额不足      
21                     curt_list.append(p_item)     #加入购物车
22                     salary -=p_item[1]         #剩余余额
23                     print("\033[31;1m%s\033[0m已经加入购物车,你的余额是\033[32;1m%s\033[0m"%(p_item[0],salary))
24                 else:
25                     print("你的余额不足")
26             else:
27                 print("你输入的商品不存在")
28         elif choice_number == "q":
29             print("——————shop list——————")
30             for i in curt_list:
31                 print(i)
32             print("您的余额是%s"%salary)
33             exit()
34         else:
35             print("你的输入有误")
36 
37 else:
38     print("你的输入有误")

字符串

name = "Zhangxin Hanchuan"

print(name.capitalize())
print(name.casefold())
print(name.center(20,"-"))
print(name.count("s"))
print(name.encode())
print(name.endswith("aa"))
print(name.find("1"))
print(name.format_map({"name":"zhangxin","age":18}))
print(name.format(name= "zhangxin",age= 19))
print(name.isalnum())  #是否阿拉伯数字+阿拉伯字符
print("abc".isalpha()) #是否纯英文字符
print("10101010".isdecimal()) #是否十进制
print("abc".isdigit()) #是否整数
print("abc".isidentifier()) #是否是合法变量名,合法标识符
print("Abc Is".islower()) #是否是小写
print("Abc Is".istitle()) #是否是大写
print("123411121".isnumeric()) #是否是数字,和isdigit没区别
print("asdfasdf".isprintable()) #是否可以打印 is tty file,drive file
print(" ".isspace()) # 是否是个空格
print("+".join(["1","2","3","4"])) # 是否是列表中加入"+" 字符
print(name.ljust(30,"-")) # 右侧补全20个字符--
print(name.lower())
print("\n   ab\n   ".strip()) #去掉空格和换行
print(name.replace("a","A"))
print(name.rfind("a"))
print(name.split("a"))
print("a+b+c+d".split("+"))
print("zhang xin".swapcase())

字典

字典(dictionary),字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

字典定义

info = {
    "stdu1101" : "Wuteng Lan",
    "stdu1102" : "Maliya XiaoZe",
    "stdu1103" : "Duoyejiyi Bo",
    "stdu1104" : "LongZe Luola",
}

字典特性

  • 字典是没有顺序的
  • key的值是唯一,天生去重复

增加

>>> info["stdu1105"]= "苍井空"
>>> info
{'stdu1101': 'Wuteng Lan', 'stdu1102': 'Maliya XiaoZe', 'stdu1103': 'Duoyejiyi Bo', 'stdu1104': 'LongZe Luola', 'stdu1105': '苍井空'}

修改

>>> info["stdu1101"]= "波多野结衣"
>>> info
{'stdu1101': '波多野结衣', 'stdu1102': 'Maliya XiaoZe', 'stdu1103': 'Duoyejiyi Bo', 'stdu1104': 'LongZe Luola', 'stdu1105': '苍井空'}

删除

>>> info.pop("stdu1101")
'波多野结衣'
>>> del info["stdu1102"] 
>>> info
{'stdu1103': 'Duoyejiyi Bo', 'stdu1104': 'LongZe Luola', 'stdu1105': '苍井空'}
>>> info.popitem()  #随机删除一个元素
('stdu1105', '苍井空')

查找

>>> info
{'stdu1103': 'Duoyejiyi Bo', 'stdu1104': 'LongZe Luola'}
>>> "stdu1103" in info  #标准查找
True
>>> info.get("stdu1103") #获取
'Duoyejiyi Bo'
>>> info["stdu1103"]  #同样获取
'Duoyejiyi Bo'>>> print(info.get("stdu1105"))#获取不存在的元素返回None
None
>>> info["stdu1105"]#获取不存在的元素返回错误
Traceback (most recent call last):
  File "<pyshell#165>", line 1, in <module>
    info["stdu1105"]
KeyError: 'stdu1105'

多层嵌套字典

>>> litle_dict = {
    "欧美": {
        "德国": ["工业4.0", "严谨"],
        "美国": ["很牛逼", "很自大"],
        "法国": ["很浪漫", "很懒"],
        "英国": ["足球流氓很多", "它要脱欧"]
    },
    "日韩": {
        "日本": ["AV不错", "汽车不错"]
    },
    "大陆": {
        "中国大陆": ["足球垃圾", "高铁牛逼"]
    }
}
>>> litle_dict
{'欧美': {'德国': ['工业4.0', '严谨'], '美国': ['很牛逼', '很自大'], '法国': ['很浪漫', '很懒'], '英国': ['足球流氓很多', '它要脱欧']}, '日韩': {'日本': ['AV不错', '汽车不错']}, '大陆': {'中国大陆': ['足球垃圾', '高铁牛逼']}}

修改

>>> litle_dict["欧美"]["美国"][1] = "特朗普"
>>> litle_dict
{'欧美': {'德国': ['工业4.0', '严谨'], '美国': ['很牛逼', '特朗普'], '法国': ['很浪漫', '很懒'], '英国': ['足球流氓很多', '它要脱欧']}, '日韩': {'日本': ['AV不错', '汽车不错']}, '大陆': {'中国大陆': ['足球垃圾', '高铁牛逼']}}

字典的其他操作

>>> info = {
    "stdu1101" : "Wuteng Lan",
    "stdu1102" : "Maliya XiaoZe",
    "stdu1103" : "Duoyejiyi Bo",
    "stdu1104" : "LongZe Luola",
}
>>> info.keys
<built-in method keys of dict object at 0x0000000002F47DC8>
>>> info.keys()   #列表的key值
dict_keys(['stdu1101', 'stdu1102', 'stdu1103', 'stdu1104'])
>>> info.values()
dict_values(['Wuteng Lan', 'Maliya XiaoZe', 'Duoyejiyi Bo', 'LongZe Luola'])
>>> info.items() 
dict_items([('stdu1101', 'Wuteng Lan'), ('stdu1102', 'Maliya XiaoZe'), ('stdu1103', 'Duoyejiyi Bo'), ('stdu1104', 'LongZe Luola')])
>>> info.setdefault("stdu1105","苍井空")  #不存在的参数设置默认值
'苍井空'
>>> info
{'stdu1101': 'Wuteng Lan', 'stdu1102': 'Maliya XiaoZe', 'stdu1103': 'Duoyejiyi Bo', 'stdu1104': 'LongZe Luola', 'stdu1105': '苍井空'}
>>> info.setdefault("stdu1101","武藤兰")#存在的参数设置默认值不生效
'Wuteng Lan'
>>> info
{'stdu1101': 'Wuteng Lan', 'stdu1102': 'Maliya XiaoZe', 'stdu1103': 'Duoyejiyi Bo', 'stdu1104': 'LongZe Luola', 'stdu1105': '苍井空'}
>>> b = {1:2,3:4,"stdu1102":"小泽玛丽亚"}
>>> info.update(b)#合并数据,并替换存在参数的数据
>>> info
{'stdu1101': 'Wuteng Lan', 'stdu1102': '小泽玛丽亚', 'stdu1103': 'Duoyejiyi Bo', 'stdu1104': 'LongZe Luola', 'stdu1105': '苍井空', 1: 2, 3: 4}
>>> dict.fromkeys([1,2,3],"test") #坑多慎用
{1: 'test', 2: 'test', 3: 'test'}

循环dict

>>> info
{'stdu1101': 'Wuteng Lan', 'stdu1102': '小泽玛丽亚', 'stdu1103': 'Duoyejiyi Bo', 'stdu1104': 'LongZe Luola', 'stdu1105': '苍井空', 1: 2, 3: 4}
>>> for key in info:
    print(key,info[key])

stdu1101 Wuteng Lan
stdu1102 小泽玛丽亚
stdu1103 Duoyejiyi Bo
stdu1104 LongZe Luola
stdu1105 苍井空
1 2
3 4
>>> for k,v in info.items(): #info内容比较大的时候 不建议使用,info.item()转换需要花费很多时间
    print(k,v)
    
stdu1101 Wuteng Lan
stdu1102 小泽玛丽亚
stdu1103 Duoyejiyi Bo
stdu1104 LongZe Luola
stdu1105 苍井空
1 2
3 4

三级菜单练习

  • 打印省、市、县三级菜单
  • 可返回上一级
  • 可随时退出程序
 1 menu = {
 2     "北京":{
 3         "通州":{
 4             "梨园":{
 5                 "蓝岛": {},
 6                 "贵友大厦": {},
 7             },
 8             "永顺":{
 9                 "京杭府": {},
10                 "北京one": {},
11             },
12             "台湖":{
13                 "印象台湖": {},
14                 "台湖政府": {},
15             },
16         },
17         "房山": {
18             "长阳": {},
19             "良乡": {},
20             "青龙湖": {},
21         },
22         "海淀": {
23             "牡丹园": {},
24             "中关村": {},
25             "学院路": {},
26         },
27 
28     },
29     "天津": {
30     },
31     "上海": {
32     },
33 }
34 
35 exit_flag = False
36 
37 while not exit_flag:
38     for a in menu:
39         print(a)
40     district = input("请输入城市名称:")
41     if district in menu:
42         while not exit_flag:
43             for b in menu[district]:
44                 print("\t",b)
45             town = input("请输入区、县名称:")
46             if town in menu[district]:
47                 while not exit_flag:
48                     for c in menu[district][town]:
49                         print("\t\t",c)
50                     hot_business_area = input("请输入城镇名称:")
51                     if hot_business_area in menu[district][town]:
52                         for d in menu[district][town][hot_business_area]:
53                             print("\t\t\t",d)
54                         end = input("最后一层了,按b返回")
55                         if end == "b":
56                             pass
57                         elif end =="q":
58                             exit_flag = True
59                     if hot_business_area == "b":
60                         break
61                     elif hot_business_area == "q":
62                         exit_flag = True
63             if town == "b":
64                 break
65             elif town == "q":
66                 exit_flag = True

 作业

一、元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
L = [11,22,33,44,55,66,77,88,99,90]
v1 = []
v2 = []
S = {"k1":v1,"k2":v2}
for s1 in L:
    # print(s1)
    if s1 <= 66:
        v1.append(s1)
    else: s1 > 66:
        v2.append(s1)
print(S)
View Code
二、查找
查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
 1 li = ["alec", " aric", "Alex", "Tony", "rain"]
 2 tu = ("alec", " aric", "Alex", "Tony", "rain")
 3 dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
 4 for i in li:
 5     j = i.strip()
 6     if (j.startswith("a") or and j.startswith("A")) j.endswith("c"):
 7         print(j)
 8 
 9 for i in tu:
10     j = i.strip()
11     if (j.startswith("a") or and j.startswith("A")) j.endswith("c"):
12         print(j)
13 
14 for keys in dic:
15     j = dic[keys].strip()
16     # print(keys,j)
17     if j.startswith("a") and j.endswith("c"):
18         print(j)
View Code
三、输出商品列表,用户输入序号,显示用户选中的商品
商品 li = ["手机", "电脑", '鼠标垫', '游艇']
 1 goods_list = ["手机","电脑","鼠标垫","游艇"]
 2 
 3 for k, v in enumerate(goods_list, 1):
 4     print(k, v)
 5 
 6 while True:
 7     number = input("请输入序号:")
 8     if number.isdigit():
 9         number = int(number)
10         if number > 0 and number <= len(goods_list):
11             print(goods_list[number-1])
12         else:
13             print("你输入的序号不存在!")
14             continue
15     else:
16         print("你输入的不是数字")
17         continue
View Code
四、购物车
功能要求:
要求用户输入总资产,例如:2000
显示商品列表,让用户根据序号选择商品,加入购物车
购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
附加:可充值、某商品移除购物车

goods = [
    {"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
 1 total = 20000
 2 shopping_cart ={}
 3 sum_shopping_price = 0
 4 goods = [
 5     {"name": "电脑", "price": 1999},
 6     {"name": "鼠标", "price": 10},
 7     {"name": "游艇", "price": 20},
 8     {"name": "美女", "price": 998},
 9 ]
10 for i in goods:
11     print(i["name"], i["price"])
12 
13 while True:
14     choice_goods = input("请选择商品:\n(结算(j):")
15     # 循环所有商品,查找需要的商品
16     if choice_goods == "j":
17         break
18     for item in goods:
19         if item["name"] == choice_goods:
20             # 选择商品加入购物车
21             name = item["name"]
22             if name not in shopping_cart.keys():
23                 shopping_cart[name] = {
24                     "single_price": item['price'],
25                     "num": 1,
26                     }
27                 print("%s加入购物车" % name)
28             else:
29                 shopping_cart[name]["num"] += 1
30                 print("%s该商品购买%s件" % (name, shopping_cart[name]["num"]))
31 # print(shopping_cart)
32 for k, v in shopping_cart.items():
33     #{
34     # '电脑': {'single_price': 1999, 'num': 1},
35     # '鼠标': {'single_price': 10, 'num': 1},
36     # '美女': {'single_price': 998, 'num': 1}
37     # }
38     x = v['single_price']
39     y = v['num']
40     single_shopping_price = x * y
41     sum_shopping_price += 1
42 
43 if sum_shopping_price < total:
44 
45     print("以下商品%s购买成功,剩余%s" % (shopping_cart,total-sum_shopping_price))
46 else:
47     print("余额不足")
View Code
五、用户交互,显示省市县三级联动的选择
dic = {
"河北": {
"石家庄": ["鹿泉", "藁城", "元氏"],
"邯郸": ["永年", "涉县", "磁县"],
},
"河南": {
"郑州": ["鹿泉1", "藁城1", "元氏1"],
"洛阳": ["永年1", "涉县1", "磁县1"],
},
"山西": {
"太远": ["鹿泉2", "藁城2", "元氏2"],
"大同": ["永年2", "涉县2", "磁县2"],
}
}
 1 dic = {
 2     "河北": {
 3         "石家庄": ["鹿泉", "藁城", "元氏"],
 4         "邯郸": ["永年", "涉县", "磁县"],
 5     },
 6     "河南": {
 7         "郑州": ["鹿泉1", "藁城1", "元氏1"],
 8         "洛阳": ["永年1", "涉县1", "磁县1"],
 9     },
10     "山西": {
11         "太远": ["鹿泉2", "藁城2", "元氏2"],
12         "大同": ["永年2", "涉县2", "磁县2"],
13     }
14 }
15 while True:
16     for k in dic:
17         print(k)
18     i1 = input("请选择省份:")
19     if i1 in dic.keys():
20         #地级市
21         one_city = dic[i1]
22         for v in one_city:
23             print(v)
24         i2 = input("请选择地级市:")
25         if i2 in one_city:
26             #县城
27             two_city = dic[i1][i2]
28             for z in two_city:
29                 print(z)
30             break
31     else:
32         print("你输入省份不存在")
33         continue
View Code

 

 

 

posted @ 2017-03-28 19:21  Ksen  阅读(404)  评论(0编辑  收藏  举报