python怎么輸出滿足條件的向量集合?
集合是無序的,天生不重復的數據組合,它的作用如下:
去重,即:把一個列表變成集合,就去重了
關系測試,即:測試兩組集合的交集、并集和差集等
一、集合常用方法總結
?
二、定義
1、語法
>>> name_1 = [1,2,3,4,7,8,7,10]
#把列表轉換為集合
>>> name_1 = set(name_1)
#轉換后,去重
>>> print(name_1,type(name_1))
{1, 2, 3, 4, 7, 8, 10}
三、關系測試
1、交集(intersection())
>>> name_1 = [1,2,3,4,7,8,7,10]
>>> name_2 = [1,3,5,8,10]
>>> name_1 = set(name_1)
>>> name_2 = set(name_2)
#輸出結果
>>> name_1.intersection(name_2)
{8, 1, 10, 3}
2、并集(union())
>>> name_1 = [1,2,3,4,7,8,7,10]
>>> name_2 = [1,3,5,8,10]
>>> name_1 = set(name_1)
>>> name_2 = set(name_2)
#輸出結果
>>> name_1.union(name_2)
{1, 2, 3, 4, 5, 7, 8, 10}
3、差集(difference())
>>> name_1 = [1,2,3,4,7,8,7,10]
>>> name_2 = [1,3,5,8,10]
>>> name_1 = set(name_1)
>>> name_2 = set(name_2)
#輸出結果
>>> name_1.difference(name_2)
{2, 4, 7}
特別提示:差集取的是數值在第一個集合中,但是不在第二個集合中(在我不在你)
4、issubset()
判斷一個集合是否是另一個集合的子集
>>> name_1 = [1,2,3,4,7,8,7,10]
>>> name_3 = [1,2,3,4]
>>> name_1 = set(name_1)
>>> name_3 = set(name_3)
#輸出結果
>>> name_3.issubset(name_1)
True
5、issuperset()
判斷一個集合是否是另一個集合的父集
>>> name_1 = [1,2,3,4,7,8,7,10]
>>> name_3 = [1,2,3,4]
>>> name_1 = set(name_1)
>>> name_3 = set(name_3)
#輸出結果
>>> name_1.issuperset(name_3)
True
6、對稱差集(symmetric_difference())
把兩個集合沒有交集的數值取出來
>>> name_1 = [1,2,3,4,7,8,7,10]
>>> name_2 = [1,3,5,8,10]
>>> name_1 = set(name_1)
>>> name_2 = set(name_2)
#輸出結果
>>> name_1.symmetric_difference(name_2)
{2, 4, 5, 7}
7、isdisjoint()
判斷兩個集合是否有交集,沒有交集,則返回True
>>> name_1 = [1,2,3,4,7,8,7,10]
>>> name_2 = [1,3,5,8,10]
>>> name_3 = [11]
>>> name_1 = set(name_1)
>>> name_2 = set(name_2)
>>> name_3 = set(name_3)
#有交集
>>> name_1.isdisjoint(name_2)
False
#無交集
>>> name_1.isdisjoint(name_3)
True