查找集合之间的全部数据与重叠数据
集合有多种方法可用于基于数学集合论进行合并、比较与分析。.union() 方法会返回一个集合,其中包含调用该方法的集合与作为参数传入的任意集合中的所有元素。您也可以使用 .intersection() 方法在集合间查找重叠数据:对一个集合调用该方法,并传入另一个集合作为参数。如果没有匹配元素,它将返回一个空集合。
在本练习中,您的任务是找出雌性与雄性企鹅物种集合的并集与交集。为此,工作区中已预加载了两个集合:female_penguin_species 和 male_penguin_species。
本练习是课程的一部分
Python 的数据类型
练习说明
- 通过计算
female_penguin_species与male_penguin_species的并集,合并所有物种。将结果保存为all_species。 - 打印
all_species中的物种数量。您可以使用len()函数计算all_species中的物种数量。 - 通过计算
female_penguin_species与male_penguin_species的交集,找出两者都出现的物种。将结果保存为overlapping_species。 - 打印
overlapping_species中的物种数量。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Find the union: all_species
all_species = ____
# Print the count of names in all_species
print(____)
# Find the intersection: overlapping_species
overlapping_species = ____
# Print the count of species in overlapping_species
print(____)