1、while循环在字典中练习
#梦幻旅游地点调查存入该字典中
survey_dict={}
#当值为true的时候 一直执行
market_survey=True
while market_survey:
name=input("请输入名字")
travle_location=input("请输入梦幻旅游地点")
survey_dict[name]=travle_location
survey_input=input("是否有人要输入")
if survey_input == "y":
market_survey=True
else:
market_survey=False
print("以下是市场调查的结果")
for user,location in survey_dict.items():
print(user,"梦幻旅游景点:",location)
结果:
请输入名字aa
请输入梦幻旅游地点AA
是否有人要输入n
以下是市场调查的结果
aa 梦幻旅游景点: AA
2、字典中fromkeys()方法
1)fromkeys()---建立字典的一个方法
seq1=['name','city']
list_dict1=dict.fromkeys(seq1)
#如果没有value,则用None当键的值
print(list_dict1)
结果:{'name': None, 'city': None}
list_dict2=dict.fromkeys(seq1,"Chigao")
print(list_dict2)
结果:{'name': 'Chigao', 'city': 'Chigao'}
3、集合–元素内容是唯一的,不可变的,但是集合本身是可变的
1) #列表去重
langes=["python","c","python",'Java',"c"]
#将langes列表去重,成为集合类型
langes_set=set(langes)
#再将集合类型转化为list类型
langes_list=list(langes_set)
print(langes_list)
结果:
['c', 'python', 'Java']
4、集合操作
1)交集 & 和 (intersection)
#有数学和物理2个夏令营
A={"Kk","Aa","Bb","Cc"}
B={"Bb","Cc","Zz","Uu"}
both1=A & B
both2=A.intersection(B) #A和B的交集
both3=B.intersection(A) #B和A的交集
print(both1)
print(both2)
print(both3)
结果:
{'Bb', 'Cc'}
{'Bb', 'Cc'}
{'Bb', 'Cc'}
2)并集 | 和 union
#有数学和物理2个夏令营
A={"Kk","Aa","Bb","Cc"}
B={"Bb","Cc","Zz","Uu"}
AorB1=A|B
AorB2=A.union(B)
BorA=B.union(A)
print(AorB1)
print(AorB2)
print(BorA)
并集结果:
{'Bb', 'Kk', 'Zz', 'Aa', 'Cc', 'Uu'}
{'Bb', 'Kk', 'Zz', 'Aa', 'Cc', 'Uu'}
{'Bb', 'Zz', 'Kk', 'Aa', 'Cc', 'Uu'}
3)差集 —和 difference
#有数学和物理2个夏令营
A={"Kk","Aa","Bb","Cc"}
B={"Bb","Cc","Zz","Uu"}
#属于A但是不属于B
Aonly1=A-B
Aonly2=A.difference(B)
print(Aonly1)
print(Aonly2)
#属于B但是不属于A
Bonly1=B-A
Bonly2=B.difference(A)
print(Bonly1)
print(Bonly2)
结果:
{'Aa', 'Kk'}
{'Aa', 'Kk'}
{'Uu', 'Zz'}
{'Uu', 'Zz'}
4)对称差集 属于A或是属于B,但没有 既属于A又属于B
#有数学和物理2个夏令营
A={"Kk","Aa","Bb","Cc"}
B={"Bb","Cc","Zz","Uu"}
A_B1=A^B
A_B2=A.symmetric_difference(B)
A_B3=B.symmetric_difference(A)
print(A_B1)
print(A_B2)
print(A_B3)
结果:
{'Uu', 'Kk', 'Zz', 'Aa'}
{'Uu', 'Kk', 'Zz', 'Aa'}
{'Uu', 'Kk', 'Aa', 'Zz'}