列表

添加 append insert

a=['sanpang','xiaohu','jinxin','wuchao']
a.append('xuepeng') 默认放到最后
a.insert(1,'xuepeng') 两个参数,插入的索引位置,插入的内容

修改

a[1]='tiantian'
a[1:3]=['a','b'] 切片法

删除 remove,pop,delete

a.remove('sanpang')
a.pop(1) 根据索引值删除对应的值
del a[0]

count

count方法统计某个元素在列表中表现的次数

extend

a=[1,2,3] b=[4,5,6]
a.extend(b) 把b添加给a
a=[1,2,3,4,5,6] b=[4,5,6]

index 根据内容找位置

a=['sanpang','xiaohu','jinxin','wuchao']
print(a.index('jinxin')) 找到jinxin的索引值

reverse 倒置

a.reverse()

sort ASCII码顺序排序

x=[4,6,2,1,7,9]
x.sort() 排序

元组
(12,)
购物车程序
salary=5000
1.iphone6s 5800
2.mackbook 9000
3.coffee 30
4.python book 80
5 .bicycle 1500
》》》:1
余额不足,-3000
》》》:5
已加入bicycle到你的购物车,当前余额:3500
》》》:quit
您已购买以下商品
bicycle 1500
coffee 32
您的余额:2970
欢迎下次光临

思路:
1.展示商品列表 2.选择购买商品 3.引导用户选择商品号 (注重交互)
嵌套
product_list=[
('Mac',9000),
('kindle',800),
('tesla',900000),
('python book',105),
('bike',2000),

]
saving=input('please input your money:') 知道自己有多少钱
shopping_car=[]
if saving.isdigit(): --校验是不是数字
saving=int(saving)
while True: --反复给用户提供商品列表选择
#打印商品内容
for i,v in enumerate(product_list,1):
print(i,'>>>>',v)

     #引导用户选择商品
    choice=input('选择购买商品编号[退出:q]:')

    #验证输入是否合法
    if choice.isdigit():  
        choice=int(choice)
        if choice>0 and choice<=len(product_list):
            #将用户选择商品通过choice取出来
            p_item=product_list[choice-1]

            #如果钱够,用本金saving减去该商品价格,并将该商品加入购物车
            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=='q':
        print('------------您已经购买如下商品----------------')
        #循环遍历购物车里的商品,购物车存放的是已买商品
        for i in shopping_car:
            print(i)
        print('您还剩%s元钱'%saving)
        break
    else:
        print('invalid input')
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容