Python 集合練習



Python 集合練習 1

Python 程式,利用集合操作查詢兩個列表中的公共元素:

l1=[1,2,3,4,5]
l2=[4,5,6,7,8]
s1=set(l1)
s2=set(l2)
commons = s1&s2 # or s1.intersection(s2)
commonlist = list(commons)
print (commonlist)

將會產生以下輸出

[4, 5]

Python 集合練習 2

Python 程式,檢查一個集合是否是另一個集合的子集:

s1={1,2,3,4,5}
s2={4,5}
if s2.issubset(s1):
   print ("s2 is a subset of s1")
else:
   print ("s2 is not a subset of s1")

將會產生以下輸出

s2 is a subset of s1

Python 集合練習 3

Python 程式,獲取列表中唯一元素的列表:

T1 = (1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2)
s1 = set(T1)
print (s1)

將會產生以下輸出

{1, 2, 3, 4, 5, 6, 7, 8, 9}
廣告