官术网_书友最值得收藏!

Sets

Sets are unordered collections of unique items. Sets are themselves mutable, we can add and remove items from them; however, the items themselves must be immutable. An important distinction with sets is that they cannot contain duplicate items. Sets are typically used to perform mathematical operations such as intersection, union, difference, and complement.

Unlike sequence types, set types do not provide any indexing or slicing operations. There are also no keys associated with values, as is the case with dictionaries. There are two types of set objects in Python, the mutable set object and the immutable frozenset object. Sets are created using comma-separated values within curly braces. By the way, we cannot create an empty set using a={}, because this will create a dictionary. To create an empty set, we write either a=set() or a=frozenset().

Methods and operations of sets are described in the following table:

In the preceding table, the parameter t can be any Python object that supports iteration and all methods are available to both set and frozenset objects. It is important to be aware that the operator versions of these methods require their arguments to be sets, whereas the methods themselves can accept any iterable type. For example, s - [1,2,3], for any set s, will generate an unsupported operand type. Using the equivalent s.difference([1,2,3]) will return a result.

Mutable set objects have additional methods, described in the following table:

The following example demonstrates some simple set operations and their results:

Notice that the set object does not care that its members are not all of the same type, as long as they are all immutable. If you try to use a mutable object such as a list or dictionaries in a set, you will receive an unhashable type error. Hashable types all have a hash value that does not change throughout the lifetime of the instance. All built-in immutable types are hashable. All built-in mutable types are not hashable, so they cannot be used as elements of sets or keys to dictionaries.

Notice also in the preceding code that when we print out the union of s1 and s2, there is only one element with the value 'ab'. This is a natural property of sets in that they do not include duplicates.

In addition to these built-in methods there are a number of other operations that we can perform on sets. For example, to test for membership of a set, use the following:

We can loop through elements in a set using the following:

主站蜘蛛池模板: 阿克苏市| 雷州市| 克东县| 邵武市| 徐闻县| 肥城市| 南昌县| 花莲县| 红河县| 于都县| 黄山市| 恭城| 方城县| 卓资县| 和平县| 榆社县| 三亚市| 建湖县| 镇安县| 乳山市| 福贡县| 肥东县| 肇东市| 昌吉市| 武义县| 京山县| 彭山县| 鹤岗市| 樟树市| 工布江达县| 海阳市| 左贡县| 沙河市| 新昌县| 荣昌县| 靖远县| 镇安县| 会昌县| 庄河市| 吴桥县| 瑞丽市|