python_列表——元组——字典——集合
列表——元组——字典——集合:
列表:
# 一:基本使用
# 1、用途:存放多个值
# 定义方式:[]内以逗号为分隔多个元素,列表内元素无类型限制
# l=['a','b','c'] #l=list(['a','b','c'])
# l1=list('hello')
# print(l1)
# 常用操作+内置的方法
# 按索引存取值(正向存取+反向存取):即可改也可以取
l = ['a', 'b', 'c']
print(id(l))
print(l[-1])
l[0] = 'A'
print(id(l))
print(l)
l[3] = 'd' # 报错
# 2、切片(顾头不顾尾,步长)
stus = [1,2,3,'a','b','c']
print(stus[1:3])
# 3、长度
# stus = [1,2,3,'a','b','c']
# print(len(stus))
# 4、成员运算in和not in
# stus = [1,2,3,'a','b','c']
# print('a' in stus)
# 5、追加
# stus = [1,2,3,'a','b','c']
# stus.append('d')
# stus.append('c')
# print(stus)
# 插入
# stus = [1,2,3,'a','b','c']
# stus.insert(1,'x')
# print(stus)
# 6、删除
# stus = [1,2,3,'a','b','c']
# del stus[1]
# print(stus)
# stus.remove('a')
# print(stus)
# stus.pop(1)
# stus.pop() # 默认删除末尾
# print(stus)
# res1=stus.remove('c') # 单纯的删除
# print(res1)
# res2=stus.pop(0) # 取走一个值
# print(res2)
# 7、循环
# stus = [1,2,3,'a','b','c']
# 依赖索引
# i=0
# while i < len(stus):
# print(stus[i])
# i+=1
# for i in range(len(stus)):
# print(i,stus[i])
# 不依赖索引
# for item in stus:
# print(item)
# 补充for循环
# for i in range(0,5,2): #0 2 4
# print(i)
# for i in range(10):#默认从零起始
# print(i)
# for i in range(10,-2,-1):
# print(i)
元组:
# 元组:相当于不可变的列表 # t = (1, 2, 3, 'a', 'b', 'c') # print(id(t[2])) # 用途:当存放的多个值,只有读的需求,没有改的需求时,可以用元组 # 常用操作: # 依赖索引 # t = (1, 2, 3, 'a', 'b', 'c') # # i = 0 # while i < len(t): # print(t[i]) # i += 1 # # for i in range(len(t)): # print(t[i]) # # # # 不依赖索引 # for item in t: # print(item) # # list('hello') # v = list(t) # v = set(t) # v = tuple(t)
字典:
# 根据数列,创建字典,并制定统一的值: dic = { 'asd': '123', 'qx': 'cac' } # v = dict.fromkeys(['asd', 113, 'gsd'],123) # v = dic['qx'] # v = dic.get('aad',12321) # v = dic.pop('aasd', 121) # v = dic.popitem() # v = dic.setdefault('qx', '12e') # v = dic.update({'qwd':'1321','fas':1231}) # print(dic) # print(v) # dic.keys() .values() .items() .get() .update()
集合:
# 定义: # s1={1,2,3, 'a', 'b', 'c'} # s2={4,5,6, 'a', 'b'} # 注意: # 集合无序 # 集合内元素不能重复 # 集合内的元素必须为不可变类型,但set集合是可变 # 用途: # 集合使用来进行关系元素,单独取集合的某一个元素是没有意义,也没有相应的方法 # # 交集:s1 & s2取两个集合的共同部分 # 差集:s1-s2,结果存于s1而不存于s2的元素集合 # 补集:s1 ^ s2,扣掉s1与s2共同部分,剩下的部分合到一起 # 并集:s1 | s2把两个合到一起,去掉重复
购物程序:
product_list=[ ('Mac Book',9000), ('Mate Book',8000), ('Magic Book',5000), ('Think Pad',4000), ('Lenovo',5000), ('SAMSUNG',7000), ('OPPO',3000), ('MI',2500), ('HUAWEI',4500), ] saving=input('请输入你的钱:') shopping_car=[] if saving.isdigit(): saving=int(saving) while True: for i,v in enumerate(product_list,1): print(i,'>>>>',v) choice=input('请选择购买的商品号:[结束购买请输入:W]: ') if choice.isdigit(): choice=int(choice) if choice>0 and choice<=len(product_list): p_item=product_list[choice-1] if p_item[1]<saving: saving-=p_item[1] shopping_car.append(p_item) else: print('余额不足,还剩%s'%saving) print(p_item) else: print('您输入的号码不正确,请重新输入') elif choice=='W': print( '------------您已经购买如下商品--------------' ) for i in shopping_car: print(i) print('您还剩%s元钱'%saving) break else: print('invalid input')