How to use Python sets?
In Python, a set is a data structure that is unordered and does not have duplicates. A set can be created using the set() function or curly braces {}.
- Create an empty set.
my_set = set()
- Create a collection that contains elements.
my_set = {1, 2, 3, 4, 5}
- Add elements to the collection.
my_set.add(6)
- Remove elements from a set.
my_set.remove(3)
- Check if the collection contains an element.
value = 4
if value in my_set:
print("集合中包含该元素")
else:
print("集合中不包含该元素")
- Iterate through the elements in the collection.
for item in my_set:
print(item)
- Create a set using set comprehension.
my_set = {x for x in range(10) if x % 2 == 0}
Please note that sets are unordered, so it is not possible to access elements in a set by index. If you need to process elements in a specific order, you can convert the set to a list or use the sorted() function to sort them.