- Mastering Python Networking
- Eric Chou
- 242字
- 2021-07-02 21:42:32
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}
>>>
- ASP.NET Core 5.0開發入門與實戰
- Learning Selenium Testing Tools with Python
- PHP+MySQL網站開發技術項目式教程(第2版)
- Python編程完全入門教程
- Getting Started with NativeScript
- Learning Laravel's Eloquent
- Visual Basic程序設計實驗指導(第二版)
- Building Android UIs with Custom Views
- Emgu CV Essentials
- Learning JavaScript Data Structures and Algorithms(Second Edition)
- 零基礎學HTML+CSS
- OpenCV with Python Blueprints
- 超簡單:用Python讓Excel飛起來(實戰150例)
- Clojure for Finance
- Hands-On ROS for Robotics Programming