python中的元组和列表操作

1、创建列表并访问:

names = ["小明", "小红", "小强", "小刚"]
print(names)
print(names[0])
print(names[1:3])     #切片
print(names[:3])     #切片
print(names[-1])      #从右边数,第一个
结果:

['小明', '小红', '小强', '小刚']

小明

['小红', '小强']

['小明', '小红', '小强']

小刚


利用value查找索引

names.index(“小明”)

 

利用value查找在列表中出现的个数

names.count(“小明”)

 

跳着输出列表:

print(names[0:-1:2])  print(names[::2])


2、往列表里添加数据

添加在后面:

names.append("小");

 

插入数据:

names.insert(1,"小怪")


3、修改直接改变值就可以了

反转数据

names.resverse()

排序方法

names.sort()


4、删除的方法

1、names.remove("小红");

2、del names[0]

3、names.pop()   #方法中可以选择删除的下标

4names.clear()     #清除所有


5、复制操作

copy

name2 = names.copy()    #浅copy,只copy第一层

name2 = copy.copy(names)

name2 = names[:]

name2 = list(names)

 

copy

name3 = copy.deepcopy(names)     #深copy


6、元组

元组一旦创建,便不能再进行修改,所以又叫只读列表

定义方式:

names = (“person1”, “person2”, “person3”)


7、一个小案例(购物车)

# Author:dancheng
product_list = [
    ("iphone", 5800),
    ("Mac Pro", 9800),
    ("Bike", 800),
    ("Coffee", 31),
    ("Alex Python", 120)
]
shop_list = []
salary = input("Input your salary:")
if salary.isdigit() :
    salary = int(salary)
    while True:
        for index,item in enumerate(product_list):
            print(index, item)
        user_choice = input("choice>>>:")
        if user_choice.isdigit():
            user_choice = int(user_choice)
            if user_choice < len(product_list) and user_choice >= 0 :
                p_item = product_list[user_choice]
                if p_item[1] <= salary:  #买的起
                    shop_list.append(p_item)
                    salary -= p_item[1]
                    print("Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m" %(p_item, salary))
                else :
                    print("money lesser")
            else:
                print("produce code [%s] is not exist!" %user_choice)
        elif user_choice == 'q' :
            print("------------shopping list---------------")
            for p in shop_list:
                print(p)
            print("Your current balance:", salary)
            exit()
        else :
            print("invalid option")
else:
    exit()




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值