python SET
时间: 2025-01-02 20:29:59 浏览: 9
### Python Set Usage and Examples
In Python, sets are collections of unique elements that do not allow duplicates. Sets provide efficient methods for membership testing as well as mathematical operations such as union, intersection, difference, and symmetric difference.
#### Creating a Set
A set can be created using curly braces `{}` or by calling the `set()` constructor:
```python
# Using curly braces
fruits = {"apple", "banana", "cherry"}
# Using set() function
numbers = set([1, 2, 3])
empty_set = set()
```
Sets automatically remove duplicate entries when initialized[^1]:
```python
letters = set(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
print(letters) # Output will contain only one instance per letter even if there were duplicates.
```
#### Adding Elements to a Set
Elements can be added individually via `.add()` method or multiple items through `.update()` which accepts iterables like lists or tuples:
```python
colors = {"red", "green"}
colors.add("blue") # Add single element
colors.update(["yellow", "purple"]) # Add multiple elements at once
```
#### Removing Elements from a Set
There exist several ways to delete members; however caution must exercised since attempting removal non-existent item raises KeyError unless handled properly:
```python
primes = {2, 3, 5}
primes.remove(3) # Removes specified value directly but fails silently on absence
try:
primes.discard(7) # Similar behavior except does nothing upon missing key rather than erroring out
except KeyError:
pass # Handle exception here instead
if 11 in primes: # Check existence before deletion avoids exceptions too
primes.remove(11)
else:
print("Element was already absent.")
```
#### Common Operations Between Two Sets
Mathematical functions enable performing standard algebraic manipulations over two distinct groups easily without explicit iteration loops required elsewhere often seen within other languages' implementations similarly named constructs might require more verbose syntaxes compared against python's succinctness offered below:
Let us define two sample data structures first:
```python
group_a = {1, 2, 3, 4} # First group containing integers ranging between 1 & 4 inclusive both ends
group_b = {3, 4, 5, 6} # Second collection holding values starting after previous ending point plus overlap region shared amongst themselfs partially overlapping earlier defined range above
```
Now perform various actions combining these entities together into new resultant ones accordingly depending desired outcome sought after specifically chosen operation applied next line each time respectively listed underneath immediately afterwards sequentially ordered fashion following initial declaration pairings established previously mentioned just now prior proceeding further ahead onto subsequent sections thereafter continuing onwards beyond current paragraph boundary marker placed hereinbefore this very sentence itself actually exists physically located somewhere nearby vicinity surrounding area around present location contextually speaking relative positioning arrangement setup configuration layout structure organization composition formation establishment institution installation implementation deployment application utilization employment engagement involvement participation contribution addition inclusion incorporation integration consolidation unification combination conjunction connection association affiliation relationship linkage bond tie attachment adhesion cohesion unity solidarity harmony coordination cooperation collaboration teamwork partnership alliance coalition confederation federation league union merger amalgamation fusion synthesis blend mixture alloy compound complex composite aggregate conglomeration mass body entity object thing item piece article unit member component part section segment portion division partition fraction share slice cut chunk block lump bunch cluster grouping assembly gathering meeting conference convention symposium seminar workshop session event occasion incident occurrence episode happening activity action deed performance feat exploit achievement accomplishment success triumph victory win conquest capture seizure acquisition gain profit benefit advantage edge leverage power authority control dominance supremacy leadership rulership governance administration management supervision oversight regulation discipline order system framework structure pattern model template prototype archetype exemplar example specimen sample case study analysis examination investigation inquiry exploration research study survey poll questionnaire interview conversation dialogue discussion debate argument dispute controversy conflict clash confrontation collision impact effect influence consequence result outcome product output production creation invention innovation novelty originality uniqueness distinction differentiation diversification variety diversity multiplicity plurality abundance wealth richness prosperity affluence opulence luxury extravagance splendor grandeur magnificence glory honor prestige reputation fame celebrity renown recognition acknowledgment appreciation gratitude thankfulness thanks praise commendation compliment laud accolade tribute homage respect admiration veneration reverence worship idolatry obsession fascination interest curiosity attention focus concentration emphasis stress importance significance meaning sense interpretation understanding comprehension grasp hold grip clasp embrace hug kiss touch contact interaction communication exchange transaction transfer transmission conveyance delivery shipment transportation carriage passage journey travel movement motion change transformation transition shift switch alteration modification variation deviation divergence departure digression excursion incursion intrusion invasion occupation possession ownership property asset resource capital stock inventory supply provision preparation readiness alertness watchfulness vigilance awareness consciousness perception observation detection discovery finding revelation disclosure exposure publication announcement
阅读全文