Python入门(五)

来源:互联网 发布:淘宝买115会员2017 编辑:程序博客网 时间:2024/06/07 22:24

字典

  1. list查找(麻烦)
students=["tom","jim","sue","ann"]scores=[70,80,85,75]indexes=[0,1,2,3]name="sue"score=0for i in indexes:    if students[i]==name:        score=score[i]print(score)              

#85
2. 字典查找,用大括号{}定义,键值对一一对应的关系

scores={}   #key-valuescores["jim"]=80scores["sue"]=85scores["ann"]=75print(scores.keys()) print(scores)         print(scores["sue"])  

#{‘ann’,’sue’,’jim’}
#{‘ann’:75,’sue’:85,’jim’:80}
#85
3. 字典中键值对的添加

students={}students["tom"]=60students["jim"]=70print(students)students={"tom":60,"jim":70}print(students)

#{‘tom’:60,’jim’:70}
#{‘tom’:60,’jim’:70}
4. 字典里键值对的修改

students={"tom":60,"jim":70}students["tom"]=65print(students)students["tom"]=students["tom"]+5print(students)

#{‘tom’:65,’jim’:70}
#{‘tom’:70,’jim’:70}
5. 键是否在字典里

students={"tom":60,"jim":70}print('toms' in students)

#false
6. 字典结构用于统计

pantry=["apple","orange","grape","apple","orange","tomato","potato","grape"]pantry_counts={}for item in pantry:    if item in pantry_counts:        pantry_counts[item]=pantry_counts[item]+1    else:        pantry_counts[item]=1 print(pantry_counts)   

{‘potato’:1,’apple’:3,’tomato’:1,’orange’:2,’grape’,’grape’:2}
7.删除
pantry.popitem()
pantry.clear()
pantry.pop()

集合类型
集合是无序、不重复的数据集合,主要作用是:去重,吧一个列表变成集合就自动去重了;关系测试,测试两组数据之前的交集、差集、并集等关系。

如何找出同时买了iPhone7和iPhone8的人?
iPhone7=[‘alex’,’rain’,’jack’,’old_driver’]
iPhone8=[‘alex’,’shanshan’,’jack’,’old_boy’]

1.创建集合
s={1,2,3,4} #空时为字典,有值为集合
s.add(2) s.add(6)
s.pop()
s.discard(1)
s.remove(2)
s.update([1,2,3,4,5]) #增加多个值

2.交集、差集、并集
iPhone7={‘alex’,’rain’,’jack’,’old_driver’}
iPhone8={‘alex’,’shanshan’,’jack’,’old_boy’}
交集:iPhone7.intersection(iphone8) ##{‘alex’,’jack’}
iPhone7 & iPhone8 ##{‘alex’,’jack’}
差集:iPhone7.difference(iphone8) ##{‘rain’,’old_driver’}
iPhone7 - iPhone8 ##{‘rain’,’old_driver’}
iPhone8.difference(iphone7) ##{‘old_boy’,’shanshan’}
iPhone8 - iPhone7 ##{‘old_boy’,’shanshan’}
并集: iPhone8.union(iphone7) ##{‘alex’,’rain’,’jack’,’old_driver’,old_boy’,’shanshan’}
iPhone8 | iPhone7 ##{‘alex’,’rain’,’jack’,’old_driver’,old_boy’,’shanshan’}
对称差集(两个集合不相交的部分的合):
iPhone8.symmetric_difference(iphone7) ##{‘rain’,,’old_driver’,old_boy’,’shanshan’}
iPhone8 ^ iPhone7 ##{‘rain’,,’old_driver’,old_boy’,’shanshan’}
子集: s.issubset(s2) #true s<=s2
s.issuperset(s2) #false s>=s2

原创粉丝点击