Python 基础-python-列表-元组-字典-集合

列表
格式: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"))

练习题:

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额
#购物车练习题
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 = {}
shopping_car = {
"iphone": {1: ["iphone", 6888, 5], 2: ["ipad", 4000, 8], 3: ["Samsung", 3000, 3]},
"variety": {1: ["headset", 50, 5], 2: ["usb_cable", 18, 8], 3: ["teacup", 60, 30]},
"clothing": {1: ["coat", 900, 5], 2: ["pants", 110, 8], 3: ["shoes", 300, 3]}
}
shop_history = {}
temporary_list = []
dict1 = {}
print("欢迎来到购物商城".center(50, '*'))
count = 0
True_False = 'True'
input_value = input("登录输入1,注册输入2,退出输入q:")

if input_value.isdigit(): # 判断输入的是否是数字
if int(input_value) == 1: # 登录流程
while True_False:
register_name = input("用户名:")
register_pwd = input("密 码:")
if register_name in reg_user.keys() and register_pwd == reg_user[register_name]['pwd']:
print("登录成功".center(40, '-'))
True_False = False
else:
count += 1
if count == 3:
exit("多次输入错误,退出程序")
else:
print("******************************")
print("用户名或者密码错误!请重新输入.")
print("******************************")
elif int(input_value) == 2: # 注册流程
while True_False:
register_name = input("用户名:")
register_pwd = input("密 码:")
register_sal = input("存入金额:")
if register_name in reg_user.keys(): # 判断用户名是否存在,存在重新输入,不存在注册成功,进入商城
print("用户已存在!重新输入")
else:
if register_sal.isdigit():
reg_user[register_name] = {"pwd": register_pwd, "money": register_sal}
user_val = open('user_mess.pkl', 'wb')
pickle.dump(reg_user, user_val)
user_val.close()
print("注册成功!".center(50, '-'))
True_False = False
else:
count += 1
if count == 3:
exit("多次输入错误,退出程序")
else:
print("存钱失败!输入正确的数字")
else:
exit("输入错误!")
elif input_value == "q":
if temporary_list:
for i in temporary_list:
print(i)
else:
print("本次没有购买任何商品哦!")
exit("谢谢您的光顾,欢迎再来")
else:
exit("Please enter the Numbers")
'''打印用户历史购物列表'''
if register_name in hist_dic.keys(): print("上次的购物列表") for i in hist_dic[register_name]: print(i)'''更新用户信息'''def update_usermessage(Salary): reg_user[register_name]["money"] = Salary user_val = open('user_mess.pkl', 'wb') pickle.dump(reg_user, user_val) user_val.close()'''更新用户已购列表'''def update_shophist(hist_list): if temporary_list: shop_history[register_name] = temporary_list file_obj = open('usershoplist.pkl', 'wb') pickle.dump(shop_history, file_obj) file_obj.close()'''充值'''def Recharge(Salary, Money): if Money.isdigit(): Salary += Money # 更新用户金额 print("充值成功,现在余额为33[31;1m [s] 33[0m" % Salary) update_usermessage(Salary) else: print("充值失败")'''打印已购商品'''def print_list(): if temporary_list: print("已购买的商品".center(50, '=')) print("商品名 数量 金额 购买时间") for i in temporary_list: print(i) print("".center(50, '=')) else: print("本次没有购买任何商品哦!")Salary = int(reg_user[register_name]["money"])print("购物车欢迎你 %s ,你的账户余额为%s" % (register_name, Salary))print("============================================")while not True_False: for i in enumerate(shopping_car): # 打印商品列表 print(i[0] + 1, '.', i[1]) dict1[i[0]] = i[1] print("============================================") print("(1)退出输入 33[31;1m q33[0m") print("(2)充值输入 33[31;1m r33[0m") print("(3)查看详细商品输入类型编号") select_type = input("请输入:") if select_type == "q": # 退出并更新 用户信息 update_usermessage(Salary) print_list() exit("欢迎下次光临") if select_type == "r": top_up = input("输入充值金额:") if top_up.isdigit(): Salary += int(top_up) # 更新用户金额 print("充值成功,现在余额为33[31;1m [%s] 33[0m" % Salary) update_usermessage(Salary) else: print("充值失败") continue if select_type.isdigit(): if int(select_type) in (1, 2, 3): BIAN = int(select_type) - 1 for j in shopping_car[dict1[BIAN]]: print(j, ':', shopping_car[dict1[BIAN]][j]) print("********************************") print("(1)输入33[31;1m b33[0m 返回上一层") print("(2)输入33[31;1m s33[0m 查询已购列表") print("(3)输入33[31;1m q33[0m 退出") print("(4)输入商品对应的序号,自动购买商品!") print('-------------------------------') Num = input("请输入:") if Num == "b": continue if Num == "q": # 如果选择退出,则判断购物车是否为空,不为空就写入到文件 print_list() update_usermessage(Salary) exit("谢谢您的光顾,欢迎再来") if Num == "s": # 选择查询,列表不为空就打印,空就提示 if temporary_list: print("已购买的商品%s,余额为%s" % (temporary_list, Salary)) else: print("购入车空空如也!赶紧去购物吧!") elif Num.isdigit() and int(Num) <= len(shopping_car[dict1[BIAN]]) and int(Num) != 0: # 购物 shop_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) Get_num = shopping_car[dict1[BIAN]].get(int(Num))[2] # 获取剩余件数 Select_Digit = input("本商品一共 %s 件,你想要购买几件:" % Get_num) # 选择输入几件 if Select_Digit.isdigit() and Get_num >= int(Select_Digit): price = shopping_car[dict1[BIAN]].get(int(Num))[1] price_sum = price * int(Select_Digit) if price_sum <= int(Salary): # 判断剩余金额是否足够 Salary = int(Salary) - price_sum # 更新余额 shopping_car[dict1[BIAN]][int(Num)][2] = int(Get_num) - int(Select_Digit) temporary_list.append((shopping_car[dict1[BIAN]].get(int(Num))[0], Select_Digit, price_sum, shop_time)) # 购物信息插入列表,供查询 print("购买成功") update_shophist(temporary_list) sel_con = input("继续购物输33[31;1m c 33[0m,退出输33[31;1m q 33[0m," "充值按33[31;1m r 33[0m,""查看已购列表输 33[31;1m s 33[0m:") if sel_con == "c": pass if sel_con == "q": update_usermessage(Salary) print_list() print("谢谢您的光顾,欢迎再来") True_False = True if sel_con == "r": top_up = input("输入充值金额:") if top_up.isdigit(): Salary += int(top_up) # 更新用户金额 print("充值成功,现在余额为33[31;1m [%s] 33[0m" % Salary) update_usermessage(Salary) else: print("充值失败") if sel_con == 's': print_list() else: print('-------------------------------------') print("你的余额为 33[31m;%s33[0m,余额不足,请充值后再购买!也可以选择价格便宜的购买" % Salary) print('-------------------------------------') if_top_up = input("是否充值?充值输入1,不充值按任意键") if if_top_up == "1": top_up = input("输入充值金额:") if top_up.isdigit(): Salary += int(top_up) # 更新用户金额 print("充值成功,现在余额为33[31;1m [%s] 33[0m" % Salary) update_usermessage(Salary) else: print("充值失败") else: print("请输入正确的件数,并且最大不能超过库存的商品件数!") else: print("请输入正确的商品序号!") else: print("无此编号") else: print("输入错误")

字典:(无序、无下标,根据key来查找对应的value)
格式:
info = {"key": "value",}

dictionary = {"n1": "5000",
             "n2": "5200",
             "n3": "2300",
             "n4": "9000"}
#查询
print(dictionary["n2"])#在知道key是什么的时候查询,如果key不存在就报错
print(dictionary.get("n5"))#如果key不存在会返回none,存在就返回value。
print("n2" in dictionary)#判断key是否存在,返回true or false py2.7中格式是 dictionary.has_key("n3")
#增加
dictionary["n2"] = "5100"
dictionary["n6"] = "800"
print(dictionary)
#删除
dictionary.pop("n7")
del dictionary["n3"]#删除已知key对应的值,不存在会报错
print(dictionary)
#修改
dictionary["n2"] = "5100"
dictionary["n6"] = "800"
#其他

#values
print(dictionary.values())#查询所有value,不输出key
#keys
print(dictionary.keys())#只输出key
#setdefault
dictionary.setdefault("n5", "100")#key若有就打印value,没有就赋新value

#update(相对于两个字典来说使用,有相同的key就替换value,无则插入)
dictionary = {"n1": "5000",
             "n2": "5200",
             "n3": "2300",
             "n4": "9000"}
dictionary1={
    "n1": "8",
    "n3": "10000",
    "n6": "100",
    "n7": "4000"
}
dictionary.update(dictionary1)
print(dictionary)
{'n2': '5200', 'n4': '9000', 'n3': '10000', 'n7': '4000', 'n1': '8', 'n6': '100'}

#items将字典转换成列表
print(dictionary.items())
dict_items([('n2', '5200'), ('n3', '2300'), ('n4', '9000'), ('n1', '5000')])


#字典循环
方法一:

for i in dictionary:
    print(i, dictionary[i])


方法二:  会把字典dictionary转换成列表list,不建议使用

for key, value in dictionary.items():
    print(key, value)

 #字典练习,三级菜单

# 三级菜单

menus = {"北京": {
    "东城区": {"景点": {"upward", "man"}, "大学": {"北大", "清华"}, "房山区": {"D中", "D南"}},
    "朝阳区": {"故宫": {}, "天安": {}, "东门": {}},
    "房山区": {}},
    "山东": {"烟台": {}, "青岛": {}, "济南": {}},
    "广州": {"东莞": {}, "广东": {}, "佛山": {}}}

# print(menus["北京"]["朝阳"])
exit_falg = True

while exit_falg:
    for i in menus:
        print(i)
    regino = input("请输入你要去什么地方!1")
    if regino in menus:
        while exit_falg:
            for i1 in menus[regino]:
                print('>>>>' + i1)
            regino1 = input("请输入你要去什么地方!2")
            if regino1 in menus[regino]:
                while exit_falg:
                    for i2 in menus[regino][regino1]:
                        print('>>>>>>>' + i2)
                    regino2 = input("请输入你要去什么地方!3")
                    if regino2 in menus[regino][regino1]:
                            for i3 in menus[regino][regino1][regino2]:
                                print('>>>>>>>>>>' + i3)
                            goback = input("最后一层,按b返回上一层!")
                            if goback == "b":
                                pass
                            else:
                                exit_falg = False
                    elif regino2 == "b":
                        break
                    else:
                        exit_falg = False
            elif regino1 == "b":
                break
            else:
                exit_falg = False
    else:
        exit_falg = False

 集合 set集合 无序,不重复序列

li = [11, 22, 33, 11, 22, 33]
# 类后面加个() 就会执行类内部的一个_init_ 方法
# list(), str(), dict(), set()
# 创建集合
se = {11, 22, 33}
print(type(se))

s = set() # 创建一个空的集合
s3 = set(li) # 转换出一个集合
print(s3) # {33, 11, 22}

# 操作集合
s = set()
s.add(123)
print(s)
s.clear()
print(s)

s1 = {11, 22, 33}
s2 = {22, 33, 44}

s3 = s1.difference(s2)   # A中存在,B中不存在
print(s3)   # 11
s4 = s1.symmetric_difference(s2)    # A中存在,B中不存在的值和 B中存在,A中不存在的值
print(s4)   # {11, 44}

s1.difference_update(s2)   # A中存在,B中不存在的值更新到新的集合中
print(s1)   # {11}
s2.symmetric_difference_update(s1)     # 差集更新到s2
s3 = s1.intersection(s2)    # 交集
s1.intersection_update(s2)  # 交集更新到s1
s5 = s1.union(s2)   # 并集
print(s5)
print(s2)   # {11, 44}
s1.discard(2222)    # 移除指定元素,不存在不报错
s1.remove(222)  # 移除指定元素, 不存在报错
new = s1.pop()    # 无参数,随机移除,并返回移除的值
lis = [1, 3, 4, 6, 6]
s1.update(lis)     # 迭代更新,相当于多次添加
print(s1)

# 练习题
old_dict = {
    "1": 8,
    "2": 4,
    "4": 2
}
new_dict = {
    "1": 4,
    "2": 4,
    "3": 2
}

old_set = set(old_dict.keys())
new_set = set(new_dict.keys())

remove_set = old_set.difference(new_dict)   # 应该删除的
add_set = new_set.difference(old_set)   # 应该增加的
update_set = new_set.intersection(old_set)  # 应该更新的

print(remove_set,add_set,update_set)

for i in remove_set:
    old_dict.pop(i)
    # del old_dict[i]

print(old_dict['2'])
print(new_set)
for i in add_set:
    old_dict[i] = new_dict[i]

for i in update_set:
    old_dict[i] = new_dict[i]

print(old_dict)


原文地址:https://www.cnblogs.com/Upward-man/p/5757790.html