Python集合定义
在{}内用逗号分隔开多个元素,集合具备以下三个特点
1:每个元素必须是不可变类型
2:集合内没有重复的元素
3:集合内元素无序
其他数据类型转换集合
info="hello"
print(set(info)) #{'l', 'e', 'o', 'h'}
info=[1,2,3,4]
print(set(info)) #{1, 2, 3, 4}
info={"name":"lgj","age":26}
print(set(info)) #{'age', 'name'}
info=(1,2,3,4)
print(set(info)) #{1, 2, 3, 4}
集合-合集|并集(|)
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
print(friends1|friends2) #{'ricky', 'egon', 'zero', 'jason', 'Jy', 'kevin'}
集合-交集(&)
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
print(friends1 & friends2) # {'jason', 'egon'}
集合-差集(-)
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
print(friends1-friends2) #{'kevin', 'zero'}
集合-差集(^)
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
print(friends1 ^ friends2) #{'kevin', 'ricky', 'Jy', 'zero'}
集合-值是否相等(==)
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
print(friends2==friends1) # False