- Mastering Python Scripting for System Administrators
- Ganesh Sanjiv Naik
- 175字
- 2021-07-02 14:00:25
Sets
A set is an unordered collection of elements with no duplicates. The basic use of a set is to check membership testing and eliminate duplicate entries. These set objects support mathematical operations, such as union, intersection, difference, and symmetric difference. We can create a set using curly braces or the set() function. If you want create an empty set, then use set(), not {}.
Here is a brief demonstration:
>>> fruits = {'Mango', 'Apple', 'Mango', 'Watermelon', 'Apple', 'Orange'}
>>> print (fruits)
{'Orange', 'Mango', 'Apple', 'Watermelon'}
>>> 'Orange' in fruits
True
>>> 'Onion' in fruits
False
>>>
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'d', 'c', 'r', 'b', 'a'}
>>> a - b
{'r', 'd', 'b'}
>>> a | b
{'d', 'c', 'r', 'b', 'm', 'a', 'z', 'l'}
>>> a & b
{'a', 'c'}
>>> a ^ b
{'r', 'd', 'b', 'm', 'z', 'l'}
Set comprehensions are also supported in Python. Refer to the following code:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
推薦閱讀
- Learning Flask Framework
- JavaFX Essentials
- Python Geospatial Development(Second Edition)
- Instant QlikView 11 Application Development
- PHP+MySQL+Dreamweaver動態網站開發實例教程
- FLL+WRO樂高機器人競賽教程:機械、巡線與PID
- OpenShift在企業中的實踐:PaaS DevOps微服務(第2版)
- Python:Master the Art of Design Patterns
- 從Java到Web程序設計教程
- QGIS Python Programming Cookbook(Second Edition)
- R語言數據可視化:科技圖表繪制
- C++ Application Development with Code:Blocks
- Mudbox 2013 Cookbook
- 零基礎學C++(升級版)
- Java設計模式深入研究