列表
格式:name = []
name = [name1, name2, name3, name4, name5]
#针对列表的操作
name.index("name1")#查询指定数值的下标值
name.count("name1")#查询指定数值的总数
name.clear("name")#清空列表
name.reverse("name")#反转列表数值
name.sort("name")#排序,优先顺序 特殊字符-数字-大写字母-小写字母
name.extend("name1")#扩展。把另一个列表的值增加到当前列表
#增加 add
name.append("name5")#追加
name.insert(1, "name1.5")#插入指定位置
#删除 delete
name.remove("name1")#根据人名删除
del name[0]#根据下标删除列表里的值
del name #删除列表
name.pop(0)#删除指定下标的值,默认是最后一个
#查询 select
print(name[0], name[2])#根据下标读取
print(name[0:2]) == print(name[:2])#切片 (连续的一段:顾头不顾尾,0和-1都可以省略)
print(name[-1])#-1 获取最后一个位置的值
print(name[-2:])#获取最后两个值,从前往后数最后一个是-1、依次是-3、-2、-1
#更改 update
name[1] = "name1.5"#更改指定下标的值
#列表copy分为深copy和浅copy
深copy 会把列表里的子列表 copy过去
name = ["name1", "name2", "name3", "name4", ["name5", "name6"]]
name1 = copy.deepcopy(name)
name[4][1] = "name7"
name[1] = "name2.1"
print(name)
print(name1)
result(结果)
['name1', 'name2.1', 'name3', 'name4', ['name5', 'name7']]
['name1', 'name2', 'name3', 'name4', ['name5', 'name6']]
浅copy 只会copy列表的第一层,如果新文件子列表里的数值更改,老文件子列表的值不会更改
name = ["name1", "name2", "name3", "name4", ["name5", "name6"]]
name1 = name.copy() = copy.copy(name) = name[:] = list(name)
name[4][1] = "name7"
name[1] = "name2.1"
print(name)
print(name1)
result(结果)
['name1', 'name2.1', 'name3', 'name4', ['name5', 'name7']]
['name1', 'name2', 'name3', 'name4', ['name5', 'name7']
元组(不可变的列表)
格式:tuple = ("tu1", "tu2")
和列表一样,不可增删改。只能查询(切片)
tuple = ("tup1", "tup2")
print(tuple.count("tup1"))
print(tuple.index("tup2"))
练习题:
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
#购物车练习题
shoplist = [[1, "iphone", 6000], [2, "mac pro", 12000], [3, "ipad air", 8000], [4, "chicken", 30], [5, "eggs", 5], [6, "bike", 500]]
mall = []
salary = int(input("please input your salary:"))
while True:
for i in range(0, len(shoplist)):
print(shoplist[i])
goodid = int(input("Please enter the number you want to buy goods:")) - 1
if int(shoplist[goodid][2]) > salary:
print("Don't buy goods you want")
else:
mall.append(shoplist[goodid])
salary = salary - shoplist[goodid][2]
yesorno = input("To continue shopping?input Y or N")
if yesorno == 'N':
print("Do you have bought the goods:%s,remaining sum:%s" % (mall, salary))
print("Thanks for coming.")
break
优化修正版本:
#优化版本
import os, pickle, time
Bool = bool(True)
'''获取已存在的用户,如不存在 赋值为空'''
if os.path.exists(r'user_mess.pkl') == Bool:
pkl_file = open('user_mess.pkl', 'rb')
reg_user = pickle.load(pkl_file)
pkl_file.close()
else:
reg_user = {}
'''获取用户的历史购物列表'''
if os.path.exists(r'usershoplist.pkl') == Bool:
dirc = open('usershoplist.pkl', 'rb')
hist_dic = pickle.load(dirc)
dirc.close()
else:
hist_dic = {}
shoppi