python学习-基础-day4-字典和集合

一,字典

字典一种key - value 的数据类型,使用就像我们上学用的字典,通过偏旁、字母来查对应页的详细内容

key必须唯一,不能重复,value允许重复;字典内元素都是无序的,没有下标。

>>> team1 = {'st1':'lao cui','st2':'lao luo','st3':'lao wang','st4':'lao chen'}
>>> team1
{'st1': 'lao cui', 'st3': 'lao wang', 'st4': 'lao chen', 'st2': 'lao luo'}

1.1 增加与修改

>>> team1
{'st1': 'lao cui', 'st3': 'lao wang', 'st4': 'lao chen', 'st2': 'lao luo'}
>>> team1['st5'] = 'xiao luo'
>>> team1
{'st1': 'lao cui', 'st3': 'lao wang', 'st5': 'xiao luo', 'st4': 'lao chen', 'st2': 'lao luo'}
>>> team1['st4'] = 'update'
>>> team1
{'st1': 'lao cui', 'st3': 'lao wang', 'st5': 'xiao luo', 'st4': 'update', 'st2': 'lao luo'}
>>>

可以看出,之前字典team1的key里面没有st5,这时候是新增一个元素,当key里面有st4时,这时是更新了原来的value

1.2 删除(pop(),del ,popitem())

>>> team1
{'st1': 'lao cui', 'st3': 'lao wang', 'st5': 'xiao luo', 'st4': 'update', 'st2': 'lao luo'}
>>> team1.pop('st4')
'update'
>>> team1
{'st1': 'lao cui', 'st3': 'lao wang', 'st5': 'xiao luo', 'st2': 'lao luo'}
>>>

>>> del team1['st5']
>>> team1
{'st1': 'lao cui', 'st3': 'lao wang', 'st2': 'lao luo'}

>>> team1.popitem()
('st1', 'lao cui')
>>> team1
{'st3': 'lao wang', 'st2': 'lao luo'}
>>>

pop()和del都是删除指定的元素,popitem()随机删除一个

1.3 查找

>>> team1
{'st1': 'lao cui', 'st3': 'lao wang', 'st4': 'lao chen', 'st2': 'lao luo'}
>>> 'st4' in team1
True

>>> 'st5' in team1
False

#####如果查找的key在字典里,返回True,否则返回False。


>>> team1.get('st4')
'lao chen'
>>> team1['st5']
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
team1['st5']
KeyError: 'st5'
>>> team1.get('st5')
>>> print(team1.get('st5'))
None
>>>

#####dict.[key]如果不存在的话会报错,但是使用get只会返回None

1.4 查找dict里的所有key和value

>>> team1
{'st1': 'lao cui', 'st3': 'lao wang', 'st4': 'lao chen', 'st2': 'lao luo'}
>>> team1.keys()
dict_keys(['st1', 'st3', 'st4', 'st2'])
>>> team1.values()
dict_values(['lao cui', 'lao wang', 'lao chen', 'lao luo'])
>>>

或者用for循环一一列出

1 team1 = {'st1':'lao cui','st2':'lao luo','st3':'lao wang','st4':'lao chen'}
2 for k in team1:
3     print(k,team1[k])
4 
5 print('OR'.center(50,'-'))
6 print(team1.items())            #会将字典转换为列表,每个key-value就是列表中的一个值
7 for k1, v in team1.items():
8     print(k,v)

输出:

st4 lao chen
st3 lao wang
st2 lao luo
st1 lao cui
------------------------OR------------------------
dict_items([('st4', 'lao chen'), ('st3', 'lao wang'), ('st2', 'lao luo'), ('st1', 'lao cui')])
st1 lao chen
st1 lao wang
st1 lao luo
st1 lao cui

1.5 setdefault

team1 = {'st1':'lao cui','st2':'lao luo','st3':'lao wang','st4':'lao chen'}

team1.setdefault('st5','insert')   #没有st5的话,就新增
team1.setdefault('st3','insert')   #有st3,就更新

print(team1)

输出:

{'st1': 'lao cui', 'st5': 'insert', 'st2': 'lao luo', 'st3': 'lao wang', 'st4': 'lao chen'}

1.6 update

>>> a['st1'] = 'update'
>>> a
{1: 'a', 2: 'b', 3: 'c', 'st1': 'update'}
>>> team1
{'st1': 'lao cui', 'st3': 'lao wang', 'st4': 'lao chen', 'st2': 'lao luo'}
>>> team1.update(a)
>>> team1
{1: 'a', 2: 'b', 3: 'c', 'st1': 'update', 'st2': 'lao luo', 'st3': 'lao wang', 'st4': 'lao chen'}
>>>

如果team1与a字典里有相同的key,那么就更新,没有的话,就添加进去

1.7 fromkey

test = dict.fromkeys([1,2,3],'a')
print(test)

输出为:
{1: 'a', 2: 'a', 3: 'a'}

a如果是个字典或者列表,那么test的某个value内部的元素改变,所有的都会改变,所以a不适合多级关系

test = dict.fromkeys([1,2,3],['a','b','c'])
print(test)
test[1] [0]= 'b'
print(test)

输出:
{1: ['b', 'b', 'c'], 2: ['b', 'b', 'c'], 3: ['b', 'b', 'c']}

 因为在内存中,列表['a','b','c']指向的是一个内存地址,里面的元素改变,内存地址不变

二、集合

集合是一个无序的,不重复的数据组合,它的主要作用如下:

  • 去重,把一个列表变成集合,就自动去重了
  • 关系测试,测试两组数据之前的交集、差集、并集等关系

集合数值{}表示

num1= set([1,2,3,4,5,6,7])  #创建一个数值集合
print(num1,type(num1))
num2 = {5,6,7,8,9,10}
print(num2,type(num2))

输出:
{1, 2, 3, 4, 5, 6, 7} <class 'set'>
{5, 6, 7, 8, 9, 10} <class 'set'>

集合会自动去重,如

>>> a = set('hello')
>>> a
{'h', 'o', 'l', 'e'}

2.1 常用操作

1 print(num1 | num2)  #求两者的并集
2 print(num1 & num2)  #求两者的交集
3 print(num1 - num2)  #求两者的差集,num1有,mum2没有的
4 print(num2 - num1)  #求两者的差集,num2有,mum1没有的
5 print(num2 ^ num1)  #求对称差集,并集-交集

输出:

1 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
2 {5, 6, 7}
3 {1, 2, 3, 4}
4 {8, 9, 10}
5 {1, 2, 3, 4, 8, 9, 10}

2.2 其它操作

增加:增加一个用add,多个用update,会自动去重。

>>> a.add('b')
>>> a
{'h', 'o', 'b', 'l', 'e'}
>>> a.update('a','b','c','d','e')
>>> a
{'e', 'b', 'd', 'a', 'l', 'c', 'h', 'o'}
>>> 
 1 >>> a.add(1)
 2 >>> a
 3 {1, 'e', 'b', 'd', 'a', 'l', 'c', 'h', 'o'}    #add(1),默认是添加了一个字符串1
 4 >>> a.update(1,2,3)      #update,不允许直接添加数字,可以用下面的两种方式
 5 Traceback (most recent call last):
 6   File "<pyshell#85>", line 1, in <module>
 7     a.update(1,2,3)
 8 TypeError: 'int' object is not iterable
 9 >>> a.update([1,2,3])
10 >>> a
11 {1, 2, 3, 'e', 'b', 'd', 'a', 'l', 'c', 'h', 'o'}
12 >>> a.update({7,8,9})
13 >>> a
14 {1, 2, 3, 'e', 8, 9, 7, 'b', 'd', 'a', 'l', 'c', 'h', 'o'}

删除:(一次只能删除一个)

>>> a.remove(2)
>>> a
{1, 3, 'e', 8, 9, 7, 'b', 'd', 'a', 'l', 'c', 'h', 'o'}

子集和父集

>>> s
{1, 2, 3}
>>> f
{1, 2, 3, 5, 'a', 'vsd'}
>>> s.issubset(f)       #f是s的父集,s是f的子集
True
>>> f.issuperset(s)
True
>>> 

判断元素是不是在集合里

>>> f
{1, 2, 3, 5, 'a', 'vsd'}
>>> 'vsd' in f
True
>>> 'aaasd' in f
False

方法和运算符的对应:

s.issubset(t)  
s <= t  
测试是否 s 中的每一个元素都在 t 中  
  
s.issuperset(t)  
s >= t  
测试是否 t 中的每一个元素都在 s 中  
  
s.union(t)  
s | t  
返回一个新的 set 包含 s 和 t 中的每一个元素  
  
s.intersection(t)  
s & t  
返回一个新的 set 包含 s 和 t 中的公共元素  
  
s.difference(t)  
s - t  
返回一个新的 set 包含 s 中有但是 t 中没有的元素  
  
s.symmetric_difference(t)  
s ^ t  
返回一个新的 set 包含 s 和 t 中不重复的元素



s.copy() 返回 set “s”的一个浅复制

>>> f_copy = f.copy()
>>> f_copy
{1, 2, 3, 'a', 5, 'vsd'}
>>> f_copy.add('new')
>>> f_copy
{1, 2, 3, 'a', 5, 'vsd', 'new'}
>>> f
{1, 2, 3, 5, 'a', 'vsd'}
>>>

 

 三、作业:

购物车程序:

1、启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表

2、允许用户根据商品编号购买商品

3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒

4、可随时退出,退出时,打印已购买商品和余额

5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示

6、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买

7、允许查询之前的消费记录


##############创建用户信息文件###############
'''
f = open('shopping.txt','w')
f.write("""
{'baijiazi':[2000,'abc123',[['Iphone',6000]]],
'tuhao':[20000,'password',[]],
'zhongguodama':[10000,'123456',[]],
'xiaoxuesheng':[200,'qwert',[]]}
""")
f.close()
'''
####################end######################
###################产品列表###################
product_list = {
1:['Iphone',6000],
5:['Mac',7200],
3:['cup',15],
4:['coffee',31],
0:['ipad',1999],
2:['bike',1500],
}
# print(product_list)
'''
user_list = {'baijiazi':[2000,'abc123',[['Iphone',6000]]],
'tuhao':[20000,'password',[]],
'zhongguodama':[10000,'123456',[]],
'xiaoxuesheng':[200,'qwert',[]]
}'''
f = open('shopping.txt','r')
user_list = f.read()
user_list = eval(user_list)
f.close()
# username = input('please in put you username:')
shopping_car = []
top = True
while top:
username = input('please in put you username:')
if username in user_list.keys():
while top:
pass_old = input("请输入密码:")
if pass_old == user_list[username][1]:
salary = user_list[username][0]
print('您的余额为:',"33[31m %s 33[0m"%salary)
# select = input('是否查询之前的购物记录:Y or N ?')
while top:
for i in product_list.keys():
print(i,product_list[i][0],product_list[i][1])
your_choice = input('选择要购买的商品编号,输入999查询之前的shopping记录>>>')
if your_choice.isdigit() and int(your_choice) < 6:
if salary >= product_list[int(your_choice)][1]:
shopping_car.append(product_list[int(your_choice)])
print("33[31m %s 33[0m"%shopping_car)
salary = salary - product_list[int(your_choice)][1]
print('您的余额为:'"33[31m %s 33[0m"%salary)
user_list[username][2].append(shopping_car)
else:
print("33[31m %s 33[0m"%shopping_car)
print("33[31m %s 33[0m"%'余额不足')

elif your_choice == 'quit':
top = False
elif your_choice == '999':
print('您之前的shopping记录为:',"33[31m %s 33[0m"%user_list[username][2])
print('您的余额:',"33[31m %s 33[0m"%salary)
else:
print('请输入正确的产品编号')
else:
print("33[32m %s 33[0m"%'密码错误')
print('您购买的商品清单:',"33[31m %s 33[0m"%shopping_car,'您的余额:',"33[31m %s 33[0m"%salary)
user_list[username][2].append(shopping_car)
user_list[username][0] = salary
# print(user_list)
elif username == 'quit':
print('欢迎下次光临')
top = False
else:
print('您是新用户')
new_pass = input('为你新建用户,请输入密码:')
if new_pass == 'quit':
top = False
while True:
new_salary = input('请输入你的rmb工资,单位元>>>')
if new_salary.isdigit():
user_list[username]=[int(new_salary),new_pass,[]]
print('用户创建成功,请重新登录')
# print(user_list)
break
elif new_salary == 'quit':
top = False
else:
print('错误的金额,请重新输入')

f1 = open('shopping.txt','w')
f1.write("%s"%user_list)
f1.close()

原文地址:https://www.cnblogs.com/cq90/p/6790297.html