集合

集合 在 Python

16 個練習

關於 集合

set 是一種_可變_且_無序_的容器,裡面存放的是hashable 的物件。 集合的成員必須互異,不能有重複的項目。 它們可以容納多種不同的資料型態,甚至可以放像是由 tuples 構成的 tuple 這種巢狀結構,只要所有元素都能_雜湊_就行。 集合也有不可變的 frozenset 版本。

集合最常用來快速移除其他資料結構或項目分組中的重複項目。 當不需要維持順序、也不需要追蹤重複項目時,集合也很適合用來做有效率的比較。

和其他容器型態(字典、陣列、元組)一樣,sets 支援:

  • 用 for item in <set> 疊代,
  • 用 in 和 not in 檢查成員,
  • 用 len() 計算長度,以及
  • 用 copy() 做淺層複製。

sets 不支援:

  • 任何形式的索引
  • 透過排序或插入來決定順序
  • 切片
  • 用 + 串接

檢查某個項目是否在 set 裡,平均來說具有常數時間複雜度;相對地,在 list 或 string 裡檢查成員時,時間複雜度會隨著資料長度增加而成長。 <set>.union()、<set>.intersection() 或 <set>.difference() 等方法,平均來說也具有常數時間複雜度。

建立集合

雖然建立集合的方式有很多種,但最直接的做法是宣告_集合字面值_、使用 set 類別的建構函式(set()),以及使用_集合推導式_。

集合字面值

set 可以直接用大括號 {},並在元素之間加上逗號,寫成_集合字面值_。 重複的項目會被默默省略:

>>> one_element = {'➕'}
{'➕'}

>>> multiple_elements = {'➕', '🔻', '🔹', '🔆'}
{'➕', '🔻', '🔹', '🔆'}

>>> multiple_duplicates =  {'Hello!', 'Hello!', 'Hello!', 
                            '¡Hola!','Привіт!', 'こんにちは!', 
                            '¡Hola!','Привіт!', 'こんにちは!'}
{'こんにちは!', '¡Hola!', 'Hello!', 'Привіт!'}

集合字面值使用的大括號和 dict 字面值相同,也就是說,要建立空的 set 時必須使用 set()。

集合建構函式

set()(set 類別的建構函式)可以搭配任何以引數傳入的 iterable 使用。 iterable 裡的元素會被逐一取出,個別加入 set。 元素的順序不會被保留,重複的項目則會被默默省略:

# To create an empty set, the constructor must be used.
>>> no_elements = set()
set()

# The tuple is unpacked & each element is added.  
# Duplicates are removed.
>>> elements_from_tuple = set(("Parrot", "Bird", 
                               334782, "Bird", "Parrot"))
{334782, 'Bird', 'Parrot'}

# The list is unpacked & each element is added.
# Duplicates are removed.
>>> elements_from_list = set([2, 3, 2, 3, 3, 3, 5, 
                              7, 11, 7, 11, 13, 13])
{2, 3, 5, 7, 11, 13}

集合推導式

和 lists 與 dicts 一樣,集合也可以透過_推導式_建立:

# First, a list with duplicates
>>> numbers = [1,2,3,4,5,6,6,5,4,8,9,9,9,2,3,12,18]

# This set comprehension squares the numbers divisible by 3
# Duplicates are removed.
>>> calculated = {item**2 for item in numbers if item % 3 == 0}
{9, 36, 81, 144, 324}

建立集合時的陷阱

因為 set 建構函式有「拆解」的行為,所以拿字串來建立集合時,結果可能會讓你意外:

# String elements (Unicode code points) are 
# iterated through and added *individually*.
>>> elements_string = set("Timbuktu")
{'T', 'b', 'i', 'k', 'm', 't', 'u'}

# Unicode separators and positioning code points 
# are also added *individually*.
>>> multiple_code_points_string = set('अभ्यास')
{'अ', 'भ', 'य', 'स', 'ा', '्'}

請記住:集合可以容納不同的資料型態,也可以容納_巢狀_的資料型態,但所有 set 元素都必須是_可雜湊_的:

# Attempting to use a list for a set member throws a TypeError
>>> lists_as_elements = {['🌈','💦'], 
                        ['☁️','⭐️','🌍'], 
                        ['⛵️', '🚲', '🚀']}

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


# Standard sets are mutable, so they cannot be hashed.
>>> sets_as_elements = {{'🌈','💦'}, 
                        {'☁️','⭐️','🌍'}, 
                        {'⛵️', '🚲', '🚀'}}

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

不過,只要改用 frozenset() 型別,就能建立由 sets 組成的 set:

# Frozensets don't have a literal form.
>>> set_1 = frozenset({'🌈','💦'})
>>> set_2 = frozenset({'☁️','⭐️','🌍'})
>>> set_3 = frozenset({'⛵️', '🚲', '🚀'})

>>> frozen_sets_as_elements = {set_1, set_2, set_3}
>>> frozen_sets_as_elements
{frozenset({'⛵️', '🚀', '🚲'}),
 frozenset({'🌈', '💦'}),
 frozenset({'☁️', '⭐️', '🌍'})}

新增與移除集合成員

可以用 <set>.add(<item>) 和 <set>.remove(<item>) 這兩個方法,從 set 新增或移除元素。 如果該項目不在 set 裡,.remove(<item>) 方法會引發 KeyError:

>>> creatures = {'crow', 'duck', 'fish', 'monkey', 'elephant'}
>>> creatures.add('beaver')
>>> creatures.remove('duck')
>>> creatures
{'beaver', 'crow', 'elephant', 'fish', 'monkey'}

# Trying to remove an item that is not present raises a KeyError
>>> creatures.remove('bear')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  KeyError: 'bear'

移除集合成員的其他策略

  • <set>.discard(<item>) 會把項目從 set 中移除,但如果該項目不存在,不會引發 KeyError。
  • <set>.clear() 會移除集合中的所有項目。
  • <set>.pop() 會移除並_回傳_一個任意的項目;如果 set 是空的,則會引發 KeyError。

集合運算

集合有各種方法,大致上對應數學上的集合運算。 這些方法大多(並非全部)都有對應的運算子版本。 方法通常可以接受任何 iterable 作為引數,而運算子則要求運算的兩邊都是 set 或 frozenset。

集合之間的成員測試

<set>.isdisjoint(<other_collection>) 方法用來測試某個 set 的元素,是否和另一個集合的元素有任何重疊。 這個方法可以接受任何 iterable 或 set 作為引數。 如果兩個集合沒有任何共同元素,它會回傳 True;如果有共用的元素,則回傳 False。

# Both mammals and additional_animals are lists.
>>> mammals = ['squirrel','dog','cat','cow', 'tiger', 'elephant']
>>> additional_animals = ['pangolin', 'panda', 'parrot', 
                          'lemur', 'tiger', 'pangolin']

# Animals is a dict.
>>> animals = {'chicken': 'white',
               'sparrow': 'grey',
               'eagle': 'brown and white',
               'albatross': 'grey and white',
               'crow': 'black',
               'elephant': 'grey', 
               'dog': 'rust',
               'cow': 'black and white',
               'tiger': 'orange and black',
               'cat': 'grey',
               'squirrel': 'black'}
               
# Birds is a set.
>>> birds = {'crow','sparrow','eagle','chicken', 'albatross'}

# Mammals and birds don't share any elements.
>>> birds.isdisjoint(mammals)
True

# There are also no shared elements between 
# additional_animals and birds.
>>> birds.isdisjoint(additional_animals)
True

# Animals and mammals have shared elements.
# **Note** The first object needs to be a set or converted to a set
# since .isdisjoint() is a set method.
>>> set(animals).isdisjoint(mammals)
False

檢查子集與超集

<set>.issubset(<other_collection>) 用來檢查 <set> 中的每個元素是否也都在 <other_collection> 裡。 運算子形式是 <set> <= <other_set>:

# Set methods will take any iterable as an argument.
# All members of birds are also members of animals.
>>> birds.issubset(animals)
True

# All members of mammals also appear in animals.
# **Note** The first object needs to be a set or converted to a set
# since .issubset() is a set method.
>>> set(mammals).issubset(animals)
True

# Both objects need to be sets to use a set operator
>>> birds <= set(mammals)
False

# A set is always a loose subset of itself.
>>> set(additional_animals) <= set(additional_animals)
True

<set>.issuperset(<other_collection>) 是 .issubset() 的反向操作。 它用來檢查 <other_collection> 中的每個元素是否也都在 <set> 裡。 運算子形式是 <set> >= <other_set>:

# All members of mammals also appear in animals.
# **Note** The first object needs to be a set or converted to a set
# since .issuperset() is a set method.
>>> set(animals).issuperset(mammals)
True

# All members of animals do not show up as members of birds.
>>> birds.issuperset(animals)
False

# Both objects need to be sets to use a set operator
>>> birds >= set(mammals)
False

# A set is always a loose superset of itself.
>>> set(animals) >= set(animals)
True

「真」子集與超集

<set> < <other_set> 和 <set> > <other_set> 用來測試_真子集_。 對 < 運算子來說,如果(<set> <= <other_set>)且(<set> != <other_set>),這個 set 就是真子集。

對 > 運算子來說,如果(<set> >= <other_set>)且(<set> != <other_set>),這個 set 就是真超集。 這些運算子沒有對應的方法:

>>> animal_names = {'albatross','cat','chicken','cow','crow','dog',
                   'eagle','elephant','sparrow','squirrel','tiger'}

>>> animals_also = {'albatross','cat','chicken','cow','crow','dog',
                   'eagle','elephant','sparrow','squirrel','tiger'}

>>> mammals = {'squirrel','dog','cat','cow', 'tiger', 'elephant'}
>>> birds   = {'crow','sparrow','eagle','chicken', 'albatross'}

>>> mammals < animal_names
True

>>> animal_names > birds
True

# A set is not a *proper subset* if set == other set.
>>> animals_also < animal_names
False

# A set is never a *proper subset* of itself
>>> animals_also < animals_also
False

集合聯集

<set>.union(*<other iterables>) 會回傳一個新的 set,內含來自 <set> 和所有 <other iterables> 的元素。 這個方法的運算子形式是 <set> | <other set 1> | <other set 2> | ... | <other set n>。

>>> perennials = {'Asparagus', 'Broccoli', 'Sweet Potato', 'Kale'}
>>> annuals = {'Corn', 'Zucchini', 'Sweet Peas', 'Summer Squash'}
>>> more_perennials = ['Radicchio', 'Rhubarb', 
                      'Spinach', 'Watercress']

# Methods will take any iterable as an argument.
>>> perennials.union(more_perennials)
{'Asparagus','Broccoli','Kale','Radicchio','Rhubarb',
'Spinach','Sweet Potato','Watercress'}

# Operators require sets.
>>> set(more_perennials) | perennials
{'Asparagus',
 'Broccoli',
 'Kale',
 'Radicchio',
 'Rhubarb',
 'Spinach',
 'Sweet Potato',
 'Watercress'}

集合差集

<set>.difference(*<other iterables>) 會回傳一個新的 set,內含原本 <set> 中不在 <others> 裡的元素。 這個方法的運算子版本是 <set> - <other set 1> - <other set 2> - ... - <other set n>。

>>> berries_and_veggies = {'Asparagus', 
                          'Broccoli', 
                          'Watercress', 
                          'Goji Berries', 
                          'Goose Berries', 
                          'Ramps', 
                          'Walking Onions', 
                          'Blackberries', 
                          'Strawberries', 
                          'Rhubarb', 
                          'Kale', 
                          'Artichokes', 
                          'Currants'}

>>> veggies = ('Asparagus', 'Broccoli', 'Watercress', 'Ramps',
               'Walking Onions', 'Rhubarb', 'Kale', 'Artichokes')

# Methods will take any iterable as an argument.
>>> berries = berries_and_veggies.difference(veggies)
{'Blackberries','Currants','Goji Berries',
 'Goose Berries', 'Strawberries'}

# Operators require sets.
>>> berries_and_veggies - berries
{'Artichokes','Asparagus','Broccoli','Kale',
'Ramps','Rhubarb','Walking Onions','Watercress'}

集合交集

<set>.intersection(*<other iterables>) 會回傳一個新的 set,內含原本 set 與所有 <others> 共同擁有的元素(換句話說,就是所有元素都相交的 set)。 這個方法的運算子版本是 <set> & <other set> & <other set 2> & ... & <other set n>

>>> perennials = {'Annatto','Asafetida','Asparagus','Azalea',
                 'Winter Savory', 'Broccoli','Curry Leaf','Fennel', 
                 'Kaffir Lime','Kale','Lavender','Mint','Oranges',
                 'Oregano', 'Tarragon', 'Wild Bergamot'}

>>> annuals = {'Corn', 'Zucchini', 'Sweet Peas', 'Marjoram', 
              'Summer Squash', 'Okra','Shallots', 'Basil', 
              'Cilantro', 'Cumin', 'Sunflower', 'Chervil', 
              'Summer Savory'}

>>> herbs = ['Annatto','Asafetida','Basil','Chervil','Cilantro',
            'Curry Leaf','Fennel','Kaffir Lime','Lavender',
            'Marjoram','Mint','Oregano','Summer Savory', 
            'Tarragon','Wild Bergamot','Wild Celery',
            'Winter Savory']


# Methods will take any iterable as an argument.
>>> perennial_herbs = perennials.intersection(herbs)
{'Annatto', 'Asafetida', 'Curry Leaf', 'Fennel', 'Kaffir Lime',
 'Lavender', 'Mint', 'Oregano', 'Wild Bergamot','Winter Savory'}

# Operators require both groups be sets.
>>> annuals & set(herbs)
 {'Basil', 'Chervil', 'Marjoram', 'Cilantro'}

集合對稱差集

<set>.symmetric_difference(<other iterable>) 會回傳一個新的 set,內含在 <set> 或 <other> 之中、但不同時在兩者之中的元素。 這個方法的運算子版本是 <set> ^ <other set>。

>>> plants_1 = {'🌲','🍈','🌵', '🥑','🌴', '🥭'}
>>> plants_2 = ('🌸','🌴', '🌺', '🌲', '🌻', '🌵')


# Methods will take any iterable as an argument.
>>> fruit_and_flowers = plants_1.symmetric_difference(plants_2)
>>> fruit_and_flowers
{'🌸', '🌺', '🍈', '🥑', '🥭','🌻' }


# Operators require both groups be sets.
>>> fruit_and_flowers ^ plants_1
{'🌲',  '🌸', '🌴', '🌵','🌺', '🌻'}

>>> fruit_and_flowers ^ set(plants_2)
{'🥭', '🌴', '🌵', '🍈', '🌲', '🥑'}
Note

對兩個以上的集合做對稱差集時,結果 set 會同時包含每個 set 獨有的元素和多個集合之間共用的元素(詳情請見維基百科上關於對稱差集 的文章)。

如果只想取得每個 set 獨有的項目,就必須另外把任兩個集合之間的交集彙整起來,再從結果中移除:

>>> one = {'black pepper','breadcrumbs','celeriac','chickpea flour',
           'flour','lemon','parsley','salt','soy sauce',
           'sunflower oil','water'}

>>> two = {'black pepper','cornstarch','garlic','ginger',
           'lemon juice','lemon zest','salt','soy sauce','sugar',
           'tofu','vegetable oil','vegetable stock','water'}

>>> three = {'black pepper','garlic','lemon juice','mixed herbs',
             'nutritional yeast', 'olive oil','salt','silken tofu',
             'smoked tofu','soy sauce','spaghetti','turmeric'}

>>> four = {'barley malt','bell pepper','cashews','flour',
            'fresh basil','garlic','garlic powder', 'honey',
            'mushrooms','nutritional yeast','olive oil','oregano',
            'red onion', 'red pepper flakes','rosemary','salt',
            'sugar','tomatoes','water','yeast'}

>>> intersections = (one & two | one & three | one & four | 
                     two & three | two & four | three & four)
...
{'black pepper','flour','garlic','lemon juice','nutritional yeast', 
'olive oil','salt','soy sauce', 'sugar','water'}

# The ^ operation will include some of the items in intersections, 
# which means it is not a "clean" symmetric difference - there
# are overlapping members.
>>> (one ^ two ^ three ^ four) & intersections
{'black pepper', 'garlic', 'soy sauce', 'water'}

# Overlapping members need to be removed in a separate step
# when there are more than two sets that need symmetric difference.
>>> (one ^ two ^ three ^ four) - intersections
...
{'barley malt','bell pepper','breadcrumbs', 'cashews','celeriac',
  'chickpea flour','cornstarch','fresh basil', 'garlic powder',
  'ginger','honey','lemon','lemon zest','mixed herbs','mushrooms',
  'oregano','parsley','red onion','red pepper flakes','rosemary',
  'silken tofu','smoked tofu','spaghetti','sunflower oil', 'tofu', 
  'tomatoes','turmeric','vegetable oil','vegetable stock','yeast'}
透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 集合

練習已鎖定

再解鎖 4 個練習,就能練習 集合