08.集合里面的元素是不可重复的;
s = {1, 2, 3, 4, 1, 2, 3}
print(s, type(s))
s1 = {1}
print(s1, type(s1))
# *******如何定义一个空集合?
s2 = {} # 默认情况是dict, 称为字典
print(s2, type(s2))
# 定义一个空集合.
s3 = set([])
print(s3, type(s3))
# 集合应用1: 列表去重
li = [1,2,3,1,2,3]
print(list(set(li)))
09.集合的特性
# 索引, 切片, 重复, 连接, 成员操作符
# 集合支持的特性只有 成员操作符, 索引, 切片, 重复, 连接,均不支持;
s = {1,2,3}
# print(s[0])
# print(s[1:])
# print(s * 3)
# print({1,2,3} + {4,5,6})
print(1 in {1,2,3})
print(1 not in {1,2,3})
# for循环
for i in s:
print(i, end='|')
print()
# for+ index
for i, v in enumerate(s):
print("index: %s, value:%s" %(i, v))
10.集合常用的方法
# s = {6, 7, 3, 1,2,3}
# # 可变, 无序数据类型
# # - 添加的顺序, 和在集合中存储的顺序不同;
#
#
#
# # 增加:
# s.add(1)
# print(s)
# # 增加多个元素
# s.update({7,8,9})
# print(s)
#
#
#20 .python通过字典间接的实现switch语句
#
#
# # 删除
# s.pop()
# print(s)
#
#
#
# # 删除指定的元素
# s.remove(2)
# print(s)
# 交集, 并集, 差集
s1 = {1, 2, 3}
s2 = {2, 3, 4}
# 并集
print("并集:", s1.union(s2))
print("并集:", s1 | s2)
# 交集
print("交集:", s1.intersection(s2))
print("交集:", s1 & s2)
# 差集20 .python通过字典间接的实现switch语句
#
print("差集:", s1.difference(s2)) # s1- (s1&s2)
print("差集:", s2.difference(s1)) # s2- (s1&s2)
print("差集:",s1-s2)
print("差集:",s2-s1)
# 对等差分: 并集-交集
print("对等差分:", s1.symmetric_difference((s2)))
print("对等差分:", s1^s2)
s3 = {1,2}
s4 = {1,2,3}
print(s3.issubset(s4))
print(s3.issuperset(s4))
print(s3.isdisjoint(s4))
12.集合应用案例
# 1. 求共同好友: 张鑫和杨月,
# zx = {'001', '002', '003'}
# yy = {'001', '005', '002'}
# zx & yy
# 2. 微信群提醒:
# xxxx与群里其他人都不是微信好友关系
# 群组: s1 s2 s3
# s1 = {s4, s5, s6}
# s2 = {s1, s3, s6}
# s3 in (s1 | s2)
# 3. 权限判断:
# 网站: 权限: s1 = {A,B, C}, 用户westos目前的权限为s2 = {A C},
# 判断: 判断westos权限是否为要求权限的父集.
13.字典的定义:
总结: 定义字典:
- 定义空字典, {}, dict()
- 赋值: d = {'key':'value', 'key1':'value1'}
- 初始化所有value值: fromkeys()
- 根据已有的数据创建字典:
users = ['user1', 'user2']
passwds = ['123', '456']
zip(users, passwds)
<zip object at 0x7f764d2c3908>
list(zip(users, passwds))
[('user1', '123'), ('user2', '456')]
userinfo = dict(zip(users, passwds))
userinfo
{'user1': '123', 'user2': '456'}
"""
s = {}
print(type(s))
s = {
'fentiao':[100, 80, 90],
'westos':[100,100,100]
}
print(s, type(s))
d = dict()
print(d, type(d))
d = dict(a=1, b=2)
print(d, type(d))
cardinfo = {
'001':'000000',
'002':'000000',
}
# 随机生成100张卡号, 卡号的格式为610 334455 001 ---610 334455 100
cards = []
for cardId in range(100):
card = "610 334455 %.3d" %(cardId+1)
cards.append(card)
print(cards)
#
print({}.fromkeys(cards))
print({}.fromkeys(cards, '666666'))
"""
# 定义空集合, 必须set(),
# {}默认的类型为字典;
d = {}
print(type(d))
# 字典: key-value值, 键值对;
# value值可以是任意数据类型: int,float,long, complex, list, tuple,set, dict
d = {
'王旭': [18, '男', "请假"],
'张龙': [18, '男', '俯卧撑']
}
print(d['张龙'])
d2 = {
'a': 1,
'b': 2
}
print(d2)
d3 = {
'a': {1, 2, 3},
'b': {2, 3, 4}
}
print(d3)
# 字典的嵌套;
students = {
'13021001': {
'name':'张龙',
'age':18,
'score':100
},
'13021003': {
'name': '张',
'age': 18,
'score': 90
}
}
print(students['13021003']['name'])
# 工厂函数;
l = list([1,2,3])
print(l)
d5 = dict(a=1, b=2)
print(d5)
#
cardinfo = {
'001':'000000',
'002':'000000'
}
# fromkeys第一个参数可以列表/tuple/str/set, 将列表的每一个元素作为字典的key值,
# 并且所有key的value值一致, 都为'000000';
print({}.fromkeys({'1', '2'}, '000000'))
# 字典必须是不可变数据类型;d = {[1,2,3]:1}(x)
# 可变数据类型:list, set, dict
# 不可变: 数值类型, str, tuple
14.字典的特性
# 索引, 切片, 重复, 连接, 成员操作符
d = dict(a=1, b=2)
print(d)
# print(d[0])
# print(d[1:])
# print(d+d)
# print(d*3)
# 成员操作符, 默认判断key值是否存在.
print('a' in d)
print(1 in d)
# for循环: 默认遍历字典的key值;
for i in d:
print(i)
for i,v in enumerate(d):
print(i, '-----', v)
15.字典的增加
d = dict(a=1, b=2)
# 添加或者更改key-value对
d['g'] = 10
d['a'] = 10
print(d)
# # update:
# # 如果key值已经存在, 更新value值;
# # 如果key值不存在, 添加key-value值;
# d.update({'a':4, 'f':1})
# print(d)
#
#
# # setdefault
# # # 如果key值已经存在, 不做修改;
# # 如果key值不存在, 添加key-value值;默认情况下value值为None
# d.setdefault('g', 10)
# print(d)
d = dict(a=1, b=2)
# pop:弹出指定key-value值
# d.pop('a')
# print(d)
# popitem
# d.popitem()
# print(d)
# del d['a']
# print(d)
d.clear()
print(d)
17。字典的修改与查看
services = {
'http':80,
'mysql':3306
}
# 查看字典里面所有的key值
print(services.keys())
# 查看字典里面所有的value值
print(services.values())
# 查看字典里面所有的key-value值
print(services.items())
# 遍历
for k,v in services.items(): # k,v = ('http', 80)
print(k , '--->', v)
for k in services:
print(k, '--->', services[k])
# 查看指定key对应的value值, 注意: key不存在, 就会报错
print(services['http'])
# print(services['https'])
#
# if 'https' in services:
# print(services['https'])
# else:
# print('key not exist')
# get方法获取指定可以对应的value值
# 如果key值存在, 返回对应的value值;
# 如果key值不存在, 默认返回None, 如果需要指定返回的值, 传值即可;
print(services.get('https', 'key not exist'))
18 字典练习
# 重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.;
# 1. 用户输入一句英文句子;
# 2. 打印出每个单词及其重复的次数;
s = input("s:") # "hello java hello python"
# hello 3
# java 2
# python 1
# 1. 把每个单词分割处理;
s_li = s.split()
print(s_li)
# 2. 通过字典存储单词和该单词出现的次数;
words_dict = {}
# 3.
# 依次循环遍历列表,
如果列表元素不在字典的key中,将元素作为key, 1作为value加入字典;
如果列表元素在字典的key中,直接更新value值, 即在原有基础上加1
li = ['hello', 'java', 'hello', 'python']
words_dict = {'hello':2,'java':1 }
for item in s_li:
if item not in words_dict:
words_dict[item] = 1
else:
# words_dict[item] = words_dict[item] + 1
words_dict[item] += 1
# 4. 打印生成的字典;
print(words_dict)
"""
# ********************* 简易方法实现**********************
from collections import defaultdict
from collections import Counter
# **************1.统计每个单词出现的次数************
# s = input('s:') # 'a b a c'
s = 'a b b b c f g w e b a c c d'
li = s.split() # ['a', 'b', 'c', 'd']
wordDict = defaultdict(int)
for word in li:
wordDict[word] += 1
print(wordDict.items())
# *******************2. 找出单词出现次数最多的3个单词**********
c = Counter(wordDict)
print(c.most_common(5))
19.列表去除
# 1. 列表去重:转换为集合
li = [1, 2, 3, 4, 65, 1, 2, 3]
print(list(set(li)))
# 2. 通过字典的方式去重
# ** 字典的key值是不能重复的.
# d = {'a':1, 'b':2}
# d['a'] = 3
li = [1, 2, 3, 4, 65, 1, 2, 3]
print({}.fromkeys(li).keys())
20 .python通过字典间接的实现switch语句
# python里面不支持switch语句;
# C/C++/Java/Javascript:switch语句是用来简化if语句的.
grade = 'B'
if grade == 'A':
print("优秀")
elif grade == 'B':
print("良好")
elif grade == 'C':
print("合格")
else:
print('无效的成绩')
"""
C++:
char grade = 'B'
switch(grade)
{
case 'A':
print('')
break
case 'B':
print('')
break
default:
print('error')
}
"""
grade = 'D'
d = {
'A': '优秀',
'B':'良好',
'C':"及格"
}
# if grade in d:
# print(d[grade])
# else:
# print("无效的成绩")
print(d.get(grade, "无效的成绩"))
"""