Python Set difference() 函数用法

2023-09-17 22:24:34

set.difference() 方法返回新集,其中包含不在作为参数传递的其他集中的唯一元素。

语法:

set.difference(*other_set)

参数:

other_set:(必需)一个或多个以逗号分隔的集合。

返回值:

返回一个新集。

下面的示例演示 set.difference() 方法。

nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 8, 8}
nums3 = nums1.difference(nums2)
nums4 = nums2.difference(nums1)
print("nums1 - nums2: ", nums3)
print("nums2 - nums1: ", nums4)

输出:

nums1 - nums2: {1, 2, 3}
nums2 - nums1: {8, 6, 7}

下面列出了两个字符串集之间的差异。

cities = {'Bangalore','Mumbai','New York','Honk Kong','Chicago'}
indianCities = {'Bangalore','Mumbai'}
nonindiancities = cities.difference(indianCities)
print("Non-Indian Cities: ", nonindiancities)

输出:

Non-Indian Cities:  {'Honk Kong', 'Chicago', 'New York'}

传递多个集合(Passing Multiple Sets)

您还可以在 difference() 方法中指定多个集,如下所示。

nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 8, 8}
nums3 = { 3, 5, 8, 9, 10}
diff = nums1.difference(nums2, nums3)
print(diff)

输出:

{1, 2}

使用 - 运算符(Using the - Operator)

-运算符也可用于计算两组的差值。

nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 8, 8}
nums3 = { 3, 5, 8, 9, 10}
diff = nums1 - nums2 - nums3
print('Numbers Differences: ', diff)
cities = {'Bangalore','Mumbai','New York','Honk Kong','Chicago'}
indianCities = {'Bangalore','Mumbai'}
nonindiancities = cities - indianCities
print("Non-Indian Cities: ", nonindiancities)

输出:

Numbers Differences: {1, 2}
Non-Indian Cities: {'Honk Kong', 'Chicago', 'New York'}

本文内容总结: