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

时间:2022-12-15 08:35:25

列表
格式: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("充值成功,现在余额为\033[31;1m [s] \033[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)退出输入 \033[31;1m q\033[0m") print("(2)充值输入 \033[31;1m r\033[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("充值成功,现在余额为\033[31;1m [%s] \033[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)输入\033[31;1m b\033[0m 返回上一层") print("(2)输入\033[31;1m s\033[0m 查询已购列表") print("(3)输入\033[31;1m q\033[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("继续购物输\033[31;1m c \033[0m,退出输\033[31;1m q \033[0m," "充值按\033[31;1m r \033[0m,""查看已购列表输 \033[31;1m s \033[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("充值成功,现在余额为\033[31;1m [%s] \033[0m" % Salary) update_usermessage(Salary) else: print("充值失败") if sel_con == 's': print_list() else: print('-------------------------------------') print("你的余额为 \033[31m;%s\033[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("充值成功,现在余额为\033[31;1m [%s] \033[0m" % Salary) update_usermessage(Salary) else: print("充值失败") else: print("请输入正确的件数,并且最大不能超过库存的商品件数!") else: print("请输入正确的商品序号!") else: print("无此编号") else: print("输入错误")

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

dictionary = {"n1": "",
"n2": "",
"n3": "",
"n4": ""}
#查询
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"] = ""
dictionary["n6"] = ""
print(dictionary)
#删除
dictionary.pop("n7")
del dictionary["n3"]#删除已知key对应的值,不存在会报错
print(dictionary)
#修改
dictionary["n2"] = ""
dictionary["n6"] = ""
#其他 #values
print(dictionary.values())#查询所有value,不输出key
#keys
print(dictionary.keys())#只输出key
#setdefault
dictionary.setdefault("n5", "")#key若有就打印value,没有就赋新value #update(相对于两个字典来说使用,有相同的key就替换value,无则插入)
dictionary = {"n1": "",
"n2": "",
"n3": "",
"n4": ""}
dictionary1={
"n1": "",
"n3": "",
"n6": "",
"n7": ""
}
dictionary.update(dictionary1)
print(dictionary)
{'n2': '', 'n4': '', 'n3': '', 'n7': '', 'n1': '', 'n6': ''} #items将字典转换成列表
print(dictionary.items())
dict_items([('n2', ''), ('n3', ''), ('n4', ''), ('n1', '')])

#字典循环
方法一:

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) #
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 = {
"": 8,
"": 4,
"": 2
}
new_dict = {
"": 4,
"": 4,
"": 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[''])
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)
														
		

Python 基础-python-列表-元组-字典-集合的更多相关文章

  1. python的学习笔记01&lowbar;4基础数据类型列表 元组 字典 集合 其他其他(for,enumerate,range&rpar;

    列表 定义:[]内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素 特性: 1.可存放多个值 2.可修改指定索引位置对应的值,可变 3.按照从左到右的顺序定义列表元素,下标从0开始顺序访问 ...

  2. Python入门基础学习&lpar;列表&sol;元组&sol;字典&sol;集合&rpar;

    Python基础学习笔记(二) 列表list---[ ](打了激素的数组,可以放入混合类型) list1 = [1,2,'请多指教',0.5] 公共的功能: len(list1) #/获取元素 lis ...

  3. python中列表 元组 字典 集合的区别

    列表 元组 字典 集合的区别是python面试中最常见的一个问题.这个问题虽然很基础,但确实能反映出面试者的基础水平. (1)列表 什么是列表呢?我觉得列表就是我们日常生活中经常见到的清单.比如,统计 ...

  4. &ast;&ast;python中列表 元组 字典 集合

    列表 元组 字典 集合的区别是python面试中最常见的一个问题.这个问题虽然很基础,但确实能反映出面试者的基础水平. 1.列表 列表是以方括号“[]”包围的数据集合,不同成员以“,”分隔. 列表的特 ...

  5. python3笔记十八:python列表元组字典集合文件操作

    一:学习内容 列表元组字典集合文件操作 二:列表元组字典集合文件操作 代码: import pickle  #数据持久性模块 #封装的方法def OptionData(data,path):    # ...

  6. python&lowbar;列表——元组——字典——集合

    列表——元组——字典——集合: 列表: # 一:基本使用# 1.用途:存放多个值 # 定义方式:[]内以逗号为分隔多个元素,列表内元素无类型限制# l=['a','b','c'] #l=list([' ...

  7. Day2 - Python基础2 列表、字典、集合

    Python之路,Day2 - Python基础2   本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一, ...

  8. Python 列表&amp&semi;元组&amp&semi;字典&amp&semi;集合

    列表(list) 有序性,可存储任意类型的值 通过偏移存取,支持索引来读取元素,第一个索引为0 ,倒数第一个索引为-1 可变性 ,支持切片.合并.删除等操作 可通过索引来向指定位置插入元素 可通过po ...

  9. python 中列表 元组 字典 集合的区别

    先看图片解释 (1)列表 什么是列表呢?我觉得列表就是我们日常生活中经常见到的清单.比如,统计过去一周我们买过的东西,把这些东西列出来,就是清单.由于我们买一种东西可能不止一次,所以清单中是允许有重复 ...

随机推荐

  1. javascript数据属性和访问器属性

    var book={ _year:2004, edition:1};Object.defineProperty(book,"year",{ get:function(){ retu ...

  2. 【BZOJ】【3613】【HEOI2014】南园满地堆轻絮

    思路题 考试结束前5.6min的时候想到……但是写挂了QAQ 其实就是(差值最大的逆序对之差+1)/2; 找逆序对其实维护一个max直接往过扫就可以了……因为逆序对是前面的数大于后面的数…… 正确性显 ...

  3. app发布流程详解

    https://developer.apple.com 1. 点击 Member Center 2. 创建应用ID 3. 创建项目 4. 在AppStore创建对应的应用 5. 创建授权文件 6. 配 ...

  4. SessionA和pplication网上聊天室的网络范例

    login.aspx码,如以下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile=&quot ...

  5. CSS-学习笔记六

    1. 自适应,响应式布局 2. pure 3. Animate

  6. 判断点在多边形内算法的C&plus;&plus;实现

    目录 1. 算法思路 2. 具体实现 3. 改进空间 1. 算法思路 判断平面内点是否在多边形内有多种算法,其中射线法是其中比较好理解的一种,而且能够支持凹多边形的情况.该算法的思路很简单,就是从目标 ...

  7. gitlab安装后吃内存的解决办法

    修改配置文件/etc/gitlab/gitlab.rb 将注释掉的这一行放开(至少为2,大致算法为cpu core数量*2 +1) # unicorn[ 然后执行如下命令: gitlab-ctl re ...

  8. 周一01&period;3Python多版本共存&amp&semi;pip环境变量设置

    python多版本共存 1.分别安装Python2.7(手动添加环境变量)与Python3.6 2.分别进入Py2与Py3文件夹中,复制python.exe,重命名为python2.exe和pytho ...

  9. 消除Warning&colon; Using a password on the command line interface can be insecure的提示

    最近在部署Zabbix时需要用脚本取得一些MySQL的返回参数,需要是numberic格式的,但是调用脚本时总是输出这一句: Warning: Using a password on the comm ...

  10. 十分钟学会Java8:lambda表达式和Stream API

    Java8 的新特性:Lambda表达式.强大的 Stream API.全新时间日期 API.ConcurrentHashMap.MetaSpace.总得来说,Java8 的新特性使 Java 的运行 ...