Python 简明教程

Python - Set Exercises

Python Set Exercise 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)

它将生成以下 output

[4, 5]

Python Set Exercise 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")

它将生成以下 output

s2 is a subset of s1

Python Set Exercise 3

获取列表中唯一元素列表的 Python 程序:

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

它将生成以下 output

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