Set comprehensions в Python предоставляют лаконичный способ для того, чтобы создавать, преобразовывать и фильтровать множества. Этот инструмент позволит писать более чистый и эффективный код, который будет легко поддерживать и читать.
Чтобы получить максимальную пользу от этого статьи, желательно знать знать такие базовые концепции Python, как циклы for, итерируемые объекты, также пригодятся list comprehensions (списковые включения) и dictionary comprehensions (словарные включения).
{element_1, element_2,..., element_N}
# Пример множества
colors = {"blue", "red", "green", "orange", "green"}
print(colors)
# {'red', 'green', 'orange', 'blue'}
colors.add("purple")
print(colors)
# {'red', 'green', 'orange', 'purple', 'blue'}
numbers = [2, 2, 1, 4, 2, 3]
print(set(numbers))
# {1, 2, 3, 4}
print(set())
# set()
unique_words = set()
text = """
Beautiful is better than ugly
Explicit is better than implicit
Simple is better than complex
Complex is better than complicated
""".lower()
for word in text.split():
unique_words.add(word)
print(unique_words)
# {
# 'beautiful',
# 'ugly',
# 'better',
# 'implicit',
# 'complicated',
# 'than',
# 'explicit',
# 'is',
# 'complex',
# 'simple'
# }
{expression for member in iterable [if condition]}
text = """
Beautiful is better than ugly
Explicit is better than implicit
Simple is better than complex
Complex is better than complicated
""".lower()
print({word for word in text.split()})
# {
# 'beautiful',
# 'ugly',
# 'better',
# 'implicit',
# 'complicated',
# 'than',
# 'explicit',
# 'is',
# 'complex',
# 'simple'
# }
print(set(text.split()))
# {
# 'beautiful',
# 'ugly',
# 'better',
# 'implicit',
# 'complicated',
# 'than',
# 'explicit',
# 'is',
# 'complex',
# 'simple'
# }
matrix = [
[9, 3, 8, 3],
[4, 5, 2, 8],
[6, 4, 3, 1],
[1, 0, 4, 5],
]
print({value**2 for row in matrix for value in row})
# {64, 1, 0, 4, 36, 9, 16, 81, 25}
tools = ["Python", "Django", "Flask", "pandas", "NumPy"]
tools_set = {tool.lower() for tool in tools}
print(tools_set)
# {'django', 'numpy', 'flask', 'pandas', 'python'}
print("python".lower() in tools_set)
# True
print("Pandas".lower() in tools_set)
# True
print("Numpy".lower() in tools_set)
# True
emails = {
" alice@example.org ",
"BOB@example.com",
"charlie@EXAMPLE.com",
"David@example.net",
" bob@example.com",
"JohnDoe@example.com",
}
print({email.strip().lower() for email in emails})
# {
# 'alice@example.org',
# 'bob@example.com',
# 'johndoe@example.com',
# 'charlie@example.com',
# 'david@example.net'
# }
emails_set = {
"alice@example.org",
"bob@example.com",
"johndoe@example.com",
"charlie@example.com",
"david@example.net",
}
print({email for email in emails_set if email.endswith(".com")})
# {'bob@example.com', 'charlie@example.com', 'johndoe@example.com'}
print(set([2, 2, 1, 4, 2, 3]))
# {1, 2, 3, 4}
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print({number**2 if number % 2 == 0 else number**3 for number in numbers})
# {64, 1, 4, 36, 100, 16, 343, 729, 27, 125}
result_set = set()
for number in numbers:
if number % 2 == 0:
value = number**2
else:
value = number**3
result_set.add(value)
print(result_set)
set_ = {number**3 for number in range(1, 11)}
print(number)
Traceback (most recent call last):
...
NameError: name 'number' is not defined
Источник: RealPython