2018-08-28字典、集合

2018-08-28  本文已影响2人  Smilebest

一、recode

1.列表

二、字典

1.字典(dict)是容器类型(也是序列),以键值对作为元素(字典里面存的数据全是以键值对的形式出现的)

{key1:value1,key2:walue2,...}

2.键值对:键:值(key:value)
3.字典是可变的(增删改)--- 可变的是字典里键值对的值和个数可变
# 1.声明字典
dict1 = {2:20,'a':54,True:20,(10,10):'begain','a':[1,2]}
print(dict1)
person1 = ['smile',20,0]         # 列表存数据不明确
2.查(获取值)
print(person2['name'],person2['age'])
dict2 = {}    # 空的字典
print(type(dict2))
b.字典.get(key)

print(person2.get('age'))

print(person2.get('sex'))       # None--python中的特殊值,代表没有
总结:确定key值肯定存在的时候用[]语法获取value。
person = {'name': '张启灵','age':36,'face_grade':90 }
# 想要获取性别sex,如果没有就默认'男’
if person.get('sex'):
    print(person['sex'])
else:
    print('男')
c.遍历
dog = {'name': '旺财', 'color': 'yellow', 'age': 5}
for key in dog:
    # 打印key
    print(key)
    print(dog[key])
3.改(修改key对应的value)
4.增(添加键值对)
5.删(删除键值对)

三、字典相关的运算

1.字典不支持'+'和'*'
2.in 和 not in
computer = {'color':'write','brand':'联想'}
print('color' in computer)
3.len()

print(len(computer))

4.字典.clear():删除字典里所有的元素(键值对)
computer.clear()
print(computer)
5.字典.copy():拷贝字典中所有的元素,放到一个新的字典中
dict1 = {'a': 1, 'b': 2}
dict2 = dict1      # 将dict1中的地址赋给dict2,两个变量指向同一块内存区域
dict3 = dict1.copy()  # 将dict1中的内容复制到一个新的内存区域中,然后将新的地址给dict3
dict1['a'] = 100
print(dict2)      #{'a': 100, 'b': 2}
print(dict3)      #{'a': 1, 'b': 2}
6.dict.fromkeys(序列,默认值 = None)
注意:默认值可以不写,写的话只能写一个
print(dict.fromkeys('abc',0))   #{'a': 0, 'b': 0, 'c': 0}
print(dict.fromkeys(['name','age','sex'],[1,2]))
7.字典.key()
all_key = dict.keys()
for key in all_key:
    print(all_key)
8.字典.values(了解)
print(dict1)
all_value = dict1.values()
print(all_value)
9.字典.items()
print(dict1.items())
for key,value in dict1.items():
    print(key,value)
10.字典.setdefault(key,默认值 = None)
dict1.setdefault('ab','abc')
dict1.setdefault('dd')
print(dict1)
11.字典1.update(字典2)
dict1 = {'aa':1,'bb':'abc','cc':True}
dict1.update({'aa':99,'bb':'你好'})
print(dict1)

四、字典和列表的组合

# 学生管理系统
# 1.一个系统可以存储多个学生
#   系统应该是一个容器:列表、字典
# 2.一个学生可以存储:姓名,电话,籍贯,专业,学号ect.
# 3.添加学生
   # 元组不能用
# 4.删除学生
# 5.修改学生的信息
#。。。。
什么时候使用列表,什么时候使用字典?
1.保存的多个数据是同一个类型的时候,用列表
2.保存的多个数据的类型不同,就使用字典
student_system = [{'name':'stu1','age':'20','tel':110},
                  {'name':'stui2','age':18,'tel':120}]
#   字典中有列表
py_class = {'class':'python1806','students':[
            {'name':'stu1','age':20,'id':110},
            {'name':'stu2','age':18,'id':120}
]}
print(py_class['class'])
# 取出第二个学生的名字
print(py_class['students'][1]['name'])
name1 = input('姓名:')
age1 = int(input('年龄:'))
id1 = input('id:')
student = {'name': name1,'age': age1, 'id': id1}
# 将学生对应的字典添加到列表中
py_class['students'].append(student)
print(py_class)
# 获取班级所有的学生
all_student = py_class['students']
# 遍历取出每个学生对应的字典
for student_dict in all_student:
    # 判断name2与取出的学生的姓名一样
    if student_dict['name'] == name2:
        all_student.remove(student_dict)
print(py_class)

五、集合

集合是python中的一种容器类型:无序的,可变的,值唯一,和数学中的集合差不多
1.声明一个集合
set1 = {1,2,'a'}
print(set1,type(set1))
set2 = set('asjbdauhaicasbja')
print(set2)

set3 = {10,True,'abc',52.01}
print(set3)
2.查(获取集合中的元素)
# 遍历获取每一个元素
for iteem in set3:
    print(iteem)
3.增(添加元素)
set3.add('good')
print(set3)
set3.update({11,1111,2121})
print(set3)
4.删
set3.remove(1111)
print(set3)

# 删除所有的元素
set3.clear()
print(set3)
5.改(改不了)
6.数学相关的集合运算

集合1 <= 集合2 :判断集合2中是否包含集合1

`print({1,2,3}>= {1})

set1 = {1,2,3,5,7}
set2 = {3,4,2,6,8}
print(set1 | set2)
print(set1 ^ set2)

list1 = [1,2,2,3,4,5,6]
list2 = [5,2,100,20,56]
result = list(set(list1) & set(list2))
print(result)

练习

from tkinter import *
from tkinter import messagebox
import random


root = Tk()
root.title('表白你,做我女票吧')
root.geometry('700x700+400+400')
a = Button(root, text="不同意",bg='red')

def call():
    messagebox._show("你的眼光还是不错的!")
    root.destroy()

b = Button(root,text='同意',command = call,bg='green')

def callback(event):
    #print("clicked at", event.x, event.y)
    i = random.randint(1, 9)
    j = random.randint(1,9)
    a.place(relx=(0.1*i),rely=(0.1*j))
    root.update()

def quit():
    messagebox.showwarning('警告', '快做选择!')
root.bind("<Button-1>", callback)
root.bind('Destroy',call)
b.pack(side='left',padx=10)
a.pack(side='right',padx=10)
c=Label(text='同意我,退出程序!',font='Arial-10')
c.pack()
#a.pack()
root.protocol("WM_DELETE_WINDOW", quit)

root.mainloop()
上一篇下一篇

猜你喜欢

热点阅读