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

Sets

A set is used to contain an unordered collection of objects. Unlike lists and tuples, sets are unordered and cannot be indexed by numbers. But there is one character that makes sets standout and useful: the elements of a set are never duplicated. Imagine if you have a list of IPs that you need to put in an access list of. The only problem in this list of IPs is that they are full of duplicates. Now, think about how you would use a loop to sort it out for the unique items, the set built-in type would allow you to eliminate the duplicate entries with just one line of code. To be honest, I do not use set that much, but when I need it, I am always very thankful this exists. Once the set or sets are created, they can be compared with each other ones using the union, intersection, and differences:

    >>> a = "hello"
>>> set(a)
{'h', 'l', 'o', 'e'}
>>> b = set([1, 1, 2, 2, 3, 3, 4, 4])
>>> b
{1, 2, 3, 4}
>>> b.add(5)
>>> b
{1, 2, 3, 4, 5}
>>> b.update(['a', 'a', 'b', 'b'])
>>> b
{1, 2, 3, 4, 5, 'b', 'a'}
>>> a = set([1, 2, 3, 4, 5])
>>> b = set([4, 5, 6, 7, 8])
>>> a.intersection(b)
{4, 5}
>>> a.union(b)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> 1 *
{1, 2, 3}
>>>
主站蜘蛛池模板: 长宁区| 广汉市| 浦县| 达孜县| 海南省| 沿河| 福泉市| 靖西县| 无锡市| 女性| 阳山县| 保德县| 道孚县| 曲麻莱县| 社会| 龙山县| 乌拉特后旗| 靖西县| 新竹市| 盘山县| 浏阳市| 贵南县| 德化县| 扶风县| 永年县| 嘉善县| 柘荣县| 遂平县| 庆安县| 高安市| 会泽县| 布尔津县| 沧源| 佛学| 吴旗县| 淳化县| 巩义市| 益阳市| 巴东县| 政和县| 建平县|