📅  最后修改于: 2023-12-03 14:46:03.950000             🧑  作者: Mango
In Python, a set is a collection of unordered elements, without duplicates. There are several ways to create a set in Python, and one of them is by using set literals.
A set literal is a notation that allows you to define a set by enclosing its elements in curly braces {}
. For example:
my_set = {1, 2, 3, 'a', 'b', 'c'}
print(my_set)
Output:
{1, 2, 3, 'a', 'b', 'c'}
my_set = {1, 2, 3, 3, 3, 'a', 'a', 'b', 'b', 'c'}
print(my_set)
Output:
{1, 2, 3, 'a', 'b', 'c'}
my_set = {2, 1, 3}
print(my_set)
Output:
{1, 2, 3}
my_set = {1, 2, 3, [4, 5, 6]} # TypeError: unhashable type: 'list'
set()
, because it would create an empty dictionary instead. To create an empty set, you must use the notation {}
.empty_set = set() # Creates an empty dictionary, not an empty set
empty_set = {} # Creates an empty dictionary, not an empty set
empty_set = set({}) # Creates an empty set
empty_set = {} # Creates an empty dictionary, not an empty set
odd_numbers = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
odd_numbers = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19} # Faster than using set([1, 3, 5, 7, 9, 11, 13, 15, 17, 19])
vowels = {'a', 'e', 'i', 'o', 'u'}
consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'}
Set literals are a convenient and efficient way to define sets in Python. They provide a compact and readable notation, and they can be created directly in memory without the need to call a constructor. However, when defining sets with complex or mutable elements, it may be necessary to use other methods, such as set comprehensions or the constructor set()
.