Python3.5--列表之深copy与浅copy、元组(下)

来源:互联网 发布:淘宝店铺氛围图是什么 编辑:程序博客网 时间:2024/06/05 03:35

1、关于直接赋值


2、关于浅复制copy


(1)实现浅copy的三种方式:

import copyperson = ["name",["a",100]]p1 = copy.copy(person)p2 = person[:]p3 = list(person)print(p1)print(p2)print(p3)#运行结果:#['name', ['a', 100]] #['name', ['a', 100]] #['name', ['a', 100]]
(2)浅copy的应用:用来创建联合账号(如:夫妻共同存款)
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author:ZhengzhengLiuimport copyperson = ["name",["saving",100]]p1 = copy.copy(person)p2 = copy.copy(person)p1[0] = "Liu"p2[0] = "Mao"p1[1][1] = 50   //当第一个人使联合账户的存款发生修改时,第二个人也能看到print(p1)print(p2)#运行结果:#['Liu', ['saving', 50]]#['Mao', ['saving', 50]]

注:浅copy只复制列表的第一层元素。

3、关于深复制deep copy


4、元组(tuple)



     元组与列表差不多,也是存一组数,只是它一旦创建便不能再修改,所以,元组又叫只读列表。
     其语法为:采用小括号
names = ("Liu","Zhang","Mao","Song")
     元组只有2个方法,count和index。






3、列表结合各种逻辑条件应用——Python3.6-购物车程序练习实例

#!/usr/bin/env python# -*- coding:utf-8 -*-# Author:ZhengzhengLiuProducts = [    ('Iphone',5800),    ('Mac',12000),    ('Bike',800),    ('Water',10)]shopping_list=[]Salary = input("Your Salary:")if Salary.isdigit():    Salary = int(Salary)    while True:        for index,i in enumerate(Products):            print(index,i)        user_choice = input("Please input the products number:")        if user_choice.isdigit():            user_choice = int(user_choice)            if user_choice < len(Products) and user_choice >=0:                if Products[user_choice][1] <= Salary:                    shopping_list.append(Products[user_choice])                    Salary -= Products[user_choice][1]                    print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m"%(Products[user_choice],Salary))                else:                    print("\033[41;1mYour balance is not enough!\033[0m" %Salary)            else:                print("Invalid input!")        elif user_choice == 'q':            print("------------Shopping List----------")            for i in shopping_list:                print(i)            print("Your current balance is:",Salary)            exit()        else:            print("invalid option!")'''输出结果为:Your Salary:345000 ('Iphone', 5800)1 ('Mac', 12000)2 ('Bike', 800)3 ('Water', 10)Please input the products number:1Added ('Mac', 12000) into shopping cart,your current balance is 225000 ('Iphone', 5800)1 ('Mac', 12000)2 ('Bike', 800)3 ('Water', 10)Please input the products number:2Added ('Bike', 800) into shopping cart,your current balance is 217000 ('Iphone', 5800)1 ('Mac', 12000)2 ('Bike', 800)3 ('Water', 10)Please input the products number:4Invalid input!0 ('Iphone', 5800)1 ('Mac', 12000)2 ('Bike', 800)3 ('Water', 10)Please input the products number:3Added ('Water', 10) into shopping cart,your current balance is 216900 ('Iphone', 5800)1 ('Mac', 12000)2 ('Bike', 800)3 ('Water', 10)Please input the products number:q------------Shopping List----------('Mac', 12000)('Bike', 800)('Water', 10)Your current balance is: 21690'''




原创粉丝点击