<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Python 集 > 原文: [https://www.programiz.com/python-programming/set](https://www.programiz.com/python-programming/set) #### 在本教程中,您將學習有關 Python 集的所有知識。 如何創建它們,從中添加元素或從中刪除元素,以及在 Python 中對集合執行的所有操作。 集合是項目的無序集合。 每個集的元素都是唯一的(沒有重復),并且必須是不可變的(無法更改)。 但是,集合本身是可變的。 我們可以從中添加或刪除項目。 集還可以用于執行數學集運算,例如并集,交集,對稱差等。 * * * ## 創建 Python 集 通過將所有項目(元素)放置在大括號`{}`中(用逗號分隔)或使用內置的`set()`函數,可以創建一個集合。 它可以具有任意數量的項目,并且它們可以具有不同的類型(整數,浮點數,元組,字符串等)。 但是集合不能具有可變元素,例如[列表](/python-programming/list),集合或[字典](/python-programming/dictionary)作為其元素。 ```py # Different types of sets in Python # set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) ``` **輸出** ```py {1, 2, 3} {1.0, (1, 2, 3), 'Hello'} ``` 也嘗試以下示例。 ```py # set cannot have duplicates # Output: {1, 2, 3, 4} my_set = {1, 2, 3, 4, 3, 2} print(my_set) # we can make set from a list # Output: {1, 2, 3} my_set = set([1, 2, 3, 2]) print(my_set) # set cannot have mutable items # here [3, 4] is a mutable list # this will cause an error. my_set = {1, 2, [3, 4]} ``` **輸出**: ```py {1, 2, 3, 4} {1, 2, 3} Traceback (most recent call last): File "<string>", line 15, in <module> my_set = {1, 2, [3, 4]} TypeError: unhashable type: 'list' ``` * * * 創建一個空集有點棘手。 空花括號`{}`將在 Python 中創建一個空字典。 為了創建沒有任何元素的集合,我們使用不帶任何參數的`set()`函數。 ```py # Distinguish set and dictionary while creating empty set # initialize a with {} a = {} # check data type of a print(type(a)) # initialize a with set() a = set() # check data type of a print(type(a)) ``` **輸出**: ```py <class 'dict'> <class 'set'> ``` * * * ## 在 Python 中修改集 集是可變的。 但是,由于它們是無序的,因此索引沒有意義。 我們無法使用索引或切片來訪問或更改集合的元素。 設置數據類型不支持它。 我們可以使用`add()`方法添加一個元素,并使用`update()`方法添加多個元素。`update()`方法可以將[元組](/python-programming/tuple),列表,[字符串](/python-programming/string)或其他集合用作其參數。 在所有情況下,都避免重復。 ```py # initialize my_set my_set = {1, 3} print(my_set) # if you uncomment line 9, # you will get an error # TypeError: 'set' object does not support indexing # my_set[0] # add an element # Output: {1, 2, 3} my_set.add(2) print(my_set) # add multiple elements # Output: {1, 2, 3, 4} my_set.update([2, 3, 4]) print(my_set) # add list and set # Output: {1, 2, 3, 4, 5, 6, 8} my_set.update([4, 5], {1, 6, 8}) print(my_set) ``` **輸出**: ```py {1, 3} {1, 2, 3} {1, 2, 3, 4} {1, 2, 3, 4, 5, 6, 8} ``` * * * ## 從集中刪除元素 可以使用`discard()`和`remove()`方法從集合中移除特定項目。 兩者之間的唯一區別是,如果元素中不存在`discard()`函數,則該集合將保持不變。 另一方面,在這種情況下,`remove()`函數將引發錯誤(如果集合中不存在元素)。 以下示例將說明這一點。 ```py # Difference between discard() and remove() # initialize my_set my_set = {1, 3, 4, 5, 6} print(my_set) # discard an element # Output: {1, 3, 5, 6} my_set.discard(4) print(my_set) # remove an element # Output: {1, 3, 5} my_set.remove(6) print(my_set) # discard an element # not present in my_set # Output: {1, 3, 5} my_set.discard(2) print(my_set) # remove an element # not present in my_set # you will get an error. # Output: KeyError my_set.remove(2) ``` **輸出**: ```py {1, 3, 4, 5, 6} {1, 3, 5, 6} {1, 3, 5} {1, 3, 5} Traceback (most recent call last): File "<string>", line 28, in <module> KeyError: 2 ``` 同樣,我們可以使用`pop()`方法刪除并返回一個項目。 由于集是無序數據類型,因此無法確定將彈出哪個項目。 這是完全任意的。 我們還可以使用`clear()`方法從集合中刪除所有項目。 ```py # initialize my_set # Output: set of unique elements my_set = set("HelloWorld") print(my_set) # pop an element # Output: random element print(my_set.pop()) # pop another element my_set.pop() print(my_set) # clear my_set # Output: set() my_set.clear() print(my_set) print(my_set) ``` **輸出**: ```py {'H', 'l', 'r', 'W', 'o', 'd', 'e'} H {'r', 'W', 'o', 'd', 'e'} set() ``` * * * ## Python 集操作 集合可用于執行數學集合運算,例如并集,交集,差和對稱差。 我們可以使用運算符或方法來做到這一點。 讓我們考慮以下兩組用于以下操作。 ```py >>> A = {1, 2, 3, 4, 5} >>> B = {4, 5, 6, 7, 8} ``` ### 并集 ![Set Union in Python](https://img.kancloud.cn/39/34/3934255a96544ed99d0882fe67087fe4_450x264.png "Set Union") Python 中的并集 `A`和`B`的并集是兩個集合中所有元素的集合。 聯合使用`|`運算符執行。 使用`union()`方法可以完成相同的操作。 ```py # Set union method # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use | operator # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B) ``` **輸出**: ```py {1, 2, 3, 4, 5, 6, 7, 8} ``` 在 Python shell 上嘗試以下示例。 ```py # use union function >>> A.union(B) {1, 2, 3, 4, 5, 6, 7, 8} # use union function on B >>> B.union(A) {1, 2, 3, 4, 5, 6, 7, 8} ``` * * * ### 交集 ![Set Intersection in Python](https://img.kancloud.cn/2f/82/2f82d26e8412de982ec3bdf217492150_450x262.png "Set Intersection") Python 中的交集 `A`和`B`的交集是在這兩組中都相同的一組元素。 交叉使用`&`運算符執行。 使用`intersection()`方法可以完成相同的操作。 ```py # Intersection of sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use & operator # Output: {4, 5} print(A & B) ``` **輸出**: ```py {4, 5} ``` 在 Python Shell 中嘗試以下程序: ```py # use intersection function on A >>> A.intersection(B) {4, 5} # use intersection function on B >>> B.intersection(A) {4, 5} ``` * * * ### 差集 ![Set Difference in Python](https://img.kancloud.cn/56/9c/569cdaae4faf3458fd8ef9c6f639ed09_450x263.png "Set Difference") Python 中的差集 集合`B`與集合`A`(`A` - `B`)的區別是僅在`A`中的一組元素,但不在`B`中。 類似地,`B` - `A`是`B`中的一組元素,但不是`A`中的一組元素。 使用`-`運算符進行區別。 使用`difference()`方法可以完成相同的操作。 ```py # Difference of two sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use - operator on A # Output: {1, 2, 3} print(A - B) ``` **輸出**: ```py {1, 2, 3} ``` 在 Python Shell 中嘗試以下程序: ```py # use difference function on A >>> A.difference(B) {1, 2, 3} # use - operator on B >>> B - A {8, 6, 7} # use difference function on B >>> B.difference(A) {8, 6, 7} ``` * * * ### 對稱差集 ![Set Symmetric Difference in Python](https://img.kancloud.cn/7c/93/7c933ea5fd3831619c7455a032e8148f_450x256.png "Set Symmetric Difference") Python 的對稱差集 `A`和`B`的對稱差異是`A`和`B`中的一組元素,但兩者都不相同(不包括交叉點)。 對稱差使用`^`運算符執行。 使用方法`symmetric_difference()`可以完成相同的操作。 ```py # Symmetric difference of two sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use ^ operator # Output: {1, 2, 3, 6, 7, 8} print(A ^ B) ``` **輸出**: ```py {1, 2, 3, 6, 7, 8} ``` 在 Python Shell 中嘗試以下程序: ```py # use symmetric_difference function on A >>> A.symmetric_difference(B) {1, 2, 3, 6, 7, 8} # use symmetric_difference function on B >>> B.symmetric_difference(A) {1, 2, 3, 6, 7, 8} ``` * * * ## 其他 Python 集方法 設置方法有很多,上面已經使用了其中的一些方法。 這是設置對象可用的所有方法的列表: | 方法 | 描述 | | --- | --- | | [`add()`](/python-programming/methods/set/add) | 將元素添加到集合中 | | [`clear()`](/python-programming/methods/set/clear) | 從集合中刪除所有元素 | | [`copy()`](/python-programming/methods/set/copy) | 返回集合的副本 | | [`difference()`](/python-programming/methods/set/difference) | 將兩個或多個集合的差返回為新集合 | | [`difference_update()`](/python-programming/methods/set/difference_update) | 從該集合中刪除另一個集合的所有元素 | | [`reject()`](/python-programming/methods/set/discard) | 如果元素是成員,則從集合中刪除它。 (如果元素不在集合中,則不執行任何操作) | | [`intersection()`](/python-programming/methods/set/intersection) | 返回兩個集合的交集作為新集合 | | [`intersection_update()`](/python-programming/methods/set/intersection_update) | 用自身和另一個的交集更新集合 | | [`isdisjoint()`](/python-programming/methods/set/isdisjoint) | 如果兩個集合的交點為空,則返回`True` | | [`issubset()`](/python-programming/methods/set/issubset) | 如果另一個集合包含此集合,則返回`True` | | [`issuperset()`](/python-programming/methods/set/issuperset) | 如果此集合包含另一個集合,則返回`True` | | [`pop()`](/python-programming/methods/set/pop) | 刪除并返回一個任意集的元素。 如果集合為空,則升起`KeyError` | | [`remove()`](/python-programming/methods/set/remove) | 從集合中刪除一個元素。 如果元素不是成員,則引發`KeyError` | | [`symmetric_difference()`](/python-programming/methods/set/symmetric_difference) | 將兩個集合的對稱差作為新集合返回 | | [`symmetric_difference_update()`](/python-programming/methods/set/symmetric_difference_update) | 用本身和另一個的對稱差異更新一個集合 | | [`union()`](/python-programming/methods/set/union) | 返回新集合中集合的并集 | | [`update()`](/python-programming/methods/set/update) | 用自身和他人的并集更新集合 | * * * ## 其他集操作 ### 集的成員資格測試 我們可以使用`in`關鍵字來測試項目是否存在于集合中。 ```py # in keyword in a set # initialize my_set my_set = set("apple") # check if 'a' is present # Output: True print('a' in my_set) # check if 'p' is present # Output: False print('p' not in my_set) ``` **輸出**: ```py True False ``` * * * ### 遍歷集 我們可以使用`for`循環遍歷集合中的每個項目。 ```py >>> for letter in set("apple"): ... print(letter) ... a p e l ``` * * * ### 集的內置函數 諸如`all()`,`any()`,`enumerate()`,`len()`,`max()`,`min()`,`sorted()`,`sum()`等內置函數通常與集合一起使用以執行不同的任務。 | 函數 | Description | | [`all()`](/python-programming/methods/built-in/all) | 如果集合的所有元素都為`true`(或者集合為空),則返回`True`。 | | [`any()`](/python-programming/methods/built-in/any) | 如果集合中的任何元素為`true`,則返回`True`。 如果集合為空,則返回`False`。 | | [`enumerate()`](/python-programming/methods/built-in/enumerate) | 返回一個枚舉對象。 它包含該集合中所有項目的索引和值對。 | | [`len()`](/python-programming/methods/built-in/len) | 返回集合中的長度(項目數)。 | | [`max()`](/python-programming/methods/built-in/max) | 返回集合中最大的項目。 | | [`min()`](/python-programming/methods/built-in/min) | 返回集合中最小的項目。 | | [`sorted()`](/python-programming/methods/built-in/sorted) | 從集合中的元素返回一個新的排序列表(不對集合本身進行排序)。 | | [`sum()`](/python-programming/methods/built-in/sum) | 返回集合中所有元素的總和。 | * * * ## Python `Frozenset` `Frozenset`是具有集合特征的新類,但是一旦分配,就不能更改其元素。 元組是不可變列表,而凍結集是不可變集。 可變的集合不可散列,因此不能用作字典鍵。 另一方面,`frozenset`是可哈希化的,可用作字典的鍵。 可以使用[`Frozenset()`](/python-programming/methods/built-in/frozenset)函數創建`Frozenset`。 此數據類型支持`copy()`,`difference()`,`intersection()`,`isdisjoint()`,`issubset()`,`issuperset()`,`symmetric_difference()`和`union()`之類的方法。 由于是不可變的,因此沒有添加或刪除元素的方法。 ```py # Frozensets # initialize A and B A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) ``` 在 Python shell 上嘗試這些示例。 ```py >>> A.isdisjoint(B) False >>> A.difference(B) frozenset({1, 2}) >>> A | B frozenset({1, 2, 3, 4, 5, 6}) >>> A.add(3) ... AttributeError: 'frozenset' object has no attribute 'add' ```
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看