列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。
列表的数据项不需要具有相同的类型
定义列表
list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"]
通过下标访问列表中的元素,下标从0开始计数
print(list1[0]) >>physics print(list1[2]) >>1997 print(list1[-1])#负数表示从后面倒着取 >>2000 print(list1[-2]) >>1997
切片:去多个元素(列表切片取元素包括前面但不包括后面)
>>> list1 = ['physics', 'chemistry', 1997, 2000,1, 2, 3, 4, 5,"a", "b", "c", "d"] >>> list1[1:4] #取下标1至4之间的元素,但不包括4 ['chemistry', 1997, 2000] >>> list1[1:-1] #取下标1至-1之间元素,但不包括-1即最后一个元素 ['chemistry', 1997, 2000, 1, 2, 3, 4, 5, 'a', 'b', 'c'] >>> list1[0:3] ['physics', 'chemistry', 1997] >>> list1[:3] #如果从头开始取,0可以忽略 ['physics', 'chemistry', 1997] >>> list1[3:] #如果想取最后一个元素,就必须不能写-1 [2000, 1, 2, 3, 4, 5, 'a', 'b', 'c', 'd'] >>> list1[3:-1] #写了-1最后一个元素取不到 [2000, 1, 2, 3, 4, 5, 'a', 'b', 'c'] >>> list1[0::2] #后面的2是代表每隔一个元素就取一个 ['physics', 1997, 1, 3, 5, 'b', 'd'] >>> list1[::2] #和上面效果相同 ['physics', 1997, 1, 3, 5, 'b', 'd']
元素追加
>>> list1 ['physics', 'chemistry', 1997, 2000, 1, 2, 3, 4, 5, 'a', 'b', 'c', 'd'] >>> list1.append("xiaoming") #append方法表示元素追加 >>> list1 ['physics', 'chemistry', 1997, 2000, 1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'xiaoming']
元素插入
>>> l=[1,2,3,4,5,6,7,8] >>> l.insert(2,9) #insert表示插入,2和9表示在下标为2的前面插入9这个数字 >>> l [1, 2, 9, 3, 4, 5, 6, 7, 8]
元素修改
>>> l [1, 2, 9, 3, 4, 5, 6, 7, 8] >>> l[2]="xiaoming" #修改元素时通过下标找到元素直接修改 >>> l [1, 2, 'xiaoming', 3, 4, 5, 6, 7, 8]
元素删除
>>> l [1, 2, 'xiaoming', 3, 4, 5, 6, 7, 8] >>> del l[2] #删除下标为2的元素 >>> l [1, 2, 3, 4, 5, 6, 7, 8] >>> del l[5] #删除下标为5的元素 >>> l [1, 2, 3, 4, 5, 7, 8] >>> l.remove(7) #删除指定下标为7的元素 >>> l [1, 2, 3, 4, 5, 8] >>> l.pop() #删除列表最后一个值 8 >>> l [1, 2, 3, 4, 5]
元素扩展
>>> l [1, 2, 3, 4, 5] >>> b=[7,8,9,10] >>> l.extend(b) #extend扩展 >>> l [1, 2, 3, 4, 5, 7, 8, 9, 10]
元素拷贝(?)
>>> l [1, 2, 3, 4, 5, 7, 8, 9, 10] >>> l_copy=l.copy() >>> l_copy [1, 2, 3, 4, 5, 7, 8, 9, 10]
元素统计
>>> l [1, 1, 2, 3, 4, 5, 6] >>> l.count(1) 2 >>> l.count(2) 1
元素排序(3.0中不同数据类型不能放在一起排序)
>>> names=['xiaoming','jack','amy','tom',1,2,3] >>> names.sort() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: int() < str() >>> names[-1]='3' >>> names[-2]='2' >>> names[-3]='1' >>> names ['amy', 'jack', 'tom', 'xiaoming', '1', '2', '3'] >>> names.sort() #相同类型进行排序 >>> names ['1', '2', '3', 'amy', 'jack', 'tom', 'xiaoming']
元素反转
>>> names ['1', '2', '3', 'amy', 'jack', 'tom', 'xiaoming'] >>> names.reverse() #反转 >>> names ['xiaoming', 'tom', 'jack', 'amy', '3', '2', '1']
获取下标
>>> names ['xiaoming', 'tom', 'jack', 'amy', '3', '2', '1'] >>> names.index('tom') 1 #返回元素的下标,如果列表中这个元素有多个只返回找到的第一个下标
2、元组
Python的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
语法:
names = ("xiaoming","jack","eric")
由于元组不能修改所以只有两个方法:count和index。
购物车程序练习:
-
启动程序后,让用户输入工资,然后打印商品列表
-
允许用户根据商品编号购买商品
-
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
-
可随时退出,退出时,打印已购买商品和余额
salary=int(input("请输入您的工资:")) shopping_list=["衬衫","牛仔裤","牛肉","咖啡","手表"] price_list=[100,500,50,300,10000] shopping=[] for i in shopping_list: print(shopping_list.index(i)+1,"、",i,"[",price_list[shopping_list.index(i)],"元]") while True: customer_chose=input("请输入您想购买的物品序列号:") if customer_chose=='q': exit("已购商品为%s,所余额为%s"%(shopping,salary)) else: customer_chose=int(customer_chose) if salary >= price_list[customer_chose - 1]: print("剁手成功,恭喜您获得宝贝%s" % shopping_list[customer_chose - 1]) salary=salary-price_list[customer_chose-1] shopping.append(shopping_list[customer_chose-1]) elif salary < price_list[customer_chose - 1]: print("不好意思您的余额为%s不够购买此商品!!!!"%salary) 还有很多问题慢慢优化!!!
3、字典
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中,键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
-
字典的特性:
-
字典是无序的
-
key必须是唯一的
-
语法:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
-
增加
>>> dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} >>> dict['xiaoming']='12345' #直接添加key和value的值 >>> dict {'Alice': '2341', 'xiaoming': '12345', 'Beth': '9102', 'Cecil': '3258'}
-
修改
>>> dict {'Alice': '2341', 'xiaoming': '12345', 'Beth': '9102', 'Cecil': '3258'} >>> dict['Beth']='12345' #根据key值来修改value的值 >>> dict {'Alice': '2341', 'xiaoming': '12345', 'Beth': '12345', 'Cecil': '3258'}
-
删除
>>> dict {'Alice': '2341', 'xiaoming': '12345', 'Beth': '12345', 'Cecil': '3258'} >>> dict.pop('Alice') #根据key值删除 '2341' >>> dict {'xiaoming': '12345', 'Beth': '12345', 'Cecil': '3258'} >>> del dict['xiaoming'] #根据key值删除 >>> dict {'Beth': '12345', 'Cecil': '3258'} >>> dict.popitem() #随机删除 ('Beth', '12345') >>> dict {'Cecil': '3258'}
-
查找
>>> dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} >>> 'Alice'in dict #标准用法 True >>> dict.get('Beth') #get获取 '9102' >>> dict['Beth'] #key值获取 '9102' >>> dict['xiaoming'] #用key值获取不存在的key时会报错 Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'xiaoming' >>> dict.get('xiaoming') #用get获取不存在的key值时什么都不返回 >>>
-
多级字典操作
d={ "美国":{ "www.facbook":["大家可以互相交流的网站!!","比较不错!"], "http://www.yahoo.com":["提供多元化服务!","挺好的!!"] }, "中国":{ "www.baidu.com":["国内知名搜索网站!!","我喜欢!!"], "wwww.sogou.com":["国内不错的搜索网站!!","经常使用!!"] } } d["中国"]["www.baidu.com"][1]+="希望毕业可以进入这样的大公司!!" print(d["中国"]["www.baidu.com"]) 结果为: ['国内知名搜索网站!!', '我喜欢!!希望毕业可以进入这样的大公司!!']
-
获得value
>>> dict {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} >>> dict.values() dict_values(['2341', '9102', '3258'])
-
获得key值
>>> dict {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} >>> dict.keys() dict_keys(['Alice', 'Beth', 'Cecil'])
-
添加字典值
>>> dict.setdefault('xiaoming','12345') '12345' >>> dict {'Alice': '2341', 'xiaoming': '12345', 'Beth': '9102', 'Cecil': '3258'}
-
更新字典值
>>> dict {'Alice': '2341', 'xiaoming': '12345', 'Beth': '9102', 'Cecil': '3258'} >>> b={1:2,3:4,'Beth':'12345'} >>> dict.update(b) >>> dict {1: 2, 3: 4, 'Beth': '12345', 'Alice': '2341', 'xiaoming': '12345', 'Cecil': '3258'}
-
获得key和value
>>> dict.items() dict_items([(1, 2), (3, 4), ('Beth', '12345'), ('Alice', '2341'), ('xiaoming', '12345'), ('Cecil', '3258')])
-
循环字典
方法一: for key in d: print(key,d[key]) 运行结果为: 中国 {'www.baidu.com': ['国内知名搜索网站!!', '我喜欢!!希望毕业可以进入这样的大公司!!'], 'wwww.sogou.com': ['国内不错的搜索网站!!', '经常使用!!']} 美国 {'www.facbook': ['大家可以互相交流的网站!!', '比较不错!'], 'http://www.yahoo.com': ['提供多元化服务!', '挺好的!!']} 方法二: for k,v in d.items(): print(k,":",v) 运行结果为: 中国 {'wwww.sogou.com': ['国内不错的搜索网站!!', '经常使用!!'], 'www.baidu.com': ['国内知名搜索网站!!', '我喜欢!!希望毕业可以进入这样的大公司!!']} 美国 {'www.facbook': ['大家可以互相交流的网站!!', '比较不错!'], 'http://www.yahoo.com': ['提供多元化服务!', '挺好的!!']}
-
三级菜单程序练习
-
打印省、市、县三级菜单
-
可返回上一级
-
可随时退出程序
dict1={ "河北省":{ "石家庄市":['井陉县','正定县', '栾城县' ,'行唐县', '灵寿县','高邑县',' 深泽县',' 赞皇县 ','无极县',' 平山县', '元氏县 ','赵县', '辛集市',' 藁城市'], "沧州市":['沧县',' 青县',' 东光县', '海兴县',' 盐山县', '肃宁县',' 南皮县', '吴桥县', '献县', '孟村县', '泊头市', '任丘市', '黄骅市', '河间市' ], "邯郸市":['邯郸县', '临漳县', '成安县', '大名县', '涉县', '磁县', '肥乡县', '永年县', '邱县', '鸡泽县', '广平县', '馆陶县', '魏县', '曲周县', '武安市'] }, "山东省":{ "济南市":['历下区','市中区','槐荫区','天桥区','历城区'], "青岛市":['市南区', '市北区', '四方区', '黄岛区'], "德州市":['陵县', '宁津县', '齐河县', '武城县', '庆云县'] } } print(dict1) while True: for k in dict1.keys(): print(k) cus_chose=input("请输入您想查询的省份:") if cus_chose== 'b': break elif cus_chose == 'q': exit() else: while True: if cus_chose in dict1: for i in dict1[cus_chose]: print(i) cus_chose1=input("请输入您想要查询的市:") if cus_chose1=='b': break elif cus_chose1=='q': exit() else: while True: if cus_chose1 in dict1[cus_chose]: for j in dict1[cus_chose][cus_chose1]: print(j) cus_chose2 = input("最后一层了!!输入b返回上一层,输入q退出:") if cus_chose2 == 'b': break elif cus_chose2 == 'q': exit() 比较low还有一些问题存在!!!
-