- List comprehension python условия
- источник данных iterable
- Возвращение результата
- Условие
- Руководство по использованию list comprehension
- Преимущества list comprehension
- Создание первого list comprehension
- Python ‘if…else’ in a List Comprehension (Examples)
- Example
- The Traditional Approach
- One-Line If-Else Statements in Python
- Example
- Should You Place If…Else Statements in List Comprehensions?
List comprehension python условия
Функциональность list comprehension предоставляет более краткий и лаконичный синтаксис для создания списков на основе других наборов данных. Она имеет следующий синтаксис:
newlist = [expression for item in iterable (if condition)]
Синтаксис list comprehension состоит из следующих компонентов:
- iterable : перебираемый источник данных, в качестве которого может выступать список, множество, последовательность, либо даже функция, которая возвращает набор данных, например, range()
- item : извлекаемый из источника данных элемент
- expression : выражение, которое возвращает некоторое значение. Это значение затем попадает в генерируемый список
- condition : условие, которому должны соответствовать извлекаемые из источника данных элементы. Если элемент НЕ удовлетворяет условию, то он НЕ выбирается. Необязательный параметр.
Рассмотрим небольшой пример. Допустим, нам надо выбрать из списка все числа, которые больше 0. В обшем случае мы бы могли написать так:
numbers = [-3, -2, -1, 0, 1, 2, 3] positive_numbers = [] for n in numbers: if n > 0: positive_numbers.append(n) print(positive_numbers) # [1, 2, 3]
Теперь изменим этот код, применив list comprehension :
numbers = [-3, -2, -1, 0, 1, 2, 3] positive_numbers = [n for n in numbers if n > 0] print(positive_numbers) # [1, 2, 3]
Выражение [n for n in numbers if n > 0] говорит выбрать из списка numbers каждый элемент в переменную n, если n больше 0 и возврать n в результирующий список.
источник данных iterable
В качестве источника данных iterable может использоваться любой перебираемый объект, например, другой список, словарь и т.д. Например, функция range() возвращает все числя нуля до указанного порога не включая:
numbers = [n for n in range(10)] print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Нередко данная конструкция применяется, чтобы создать из словаря список. Например, выберем из словаря все ключи:
dictionary = words = [word for word in dictionary] print(words) # ['red', 'blue', 'green']
Возвращение результата
Параметр expression представляет выражение, которое возвращает некоторое значение. Это значение затем помещается в генерируемый список. В примерах выше это был текущий элемент, который извлекается из источника данных:
numbers = [-3, -2, -1, 0, 1, 2, 3] new_numbers = [n for n in numbers] print(new_numbers) # [-3, -2, -1, 0, 1, 2, 3]
Так, в данном случае параметр expression представляет непосредственно извлекаемый из списка numbers элемент n. Но это могут быть и более сложные значения. Например, возвратим удвоенное значение числа:
numbers = [-3, -2, -1, 0, 1, 2, 3] new_numbers = [n * 2 for n in numbers] print(new_numbers) # [-6, -4, -2, 0, 2, 4, 6]
Здесь expression представляет выражение n * 2
Это могут быть и более сложные выражения:
numbers = [-3, -2, -1, 0, 1, 2, 3] new_numbers = [n * 2 if n > 0 else n for n in numbers] print(new_numbers) # [-3, -2, -1, 0, 2, 4, 6]
Здесь параметр expression представляет выражение n * 2 if n > 0 else n . В данном случае мы говорим возвратить значение n * 2, если n > 0, иначе возвратить n.
В expression можно производить различные трансформации с данными. Например, возвратим также из словаря значение по ключу:
dictionary = words = [f": " for key in dictionary] print(words) # ['red: красный', 'blue: синий', 'green: зеленый']
Условие
Условие — параметр condition определяет фильтр для выбора элементов из источника данных. Применим условие для конкретизации выборки, например, выберем только четные числа:
numbers = [n for n in range(10) if n % 2 == 0] print(numbers) # [0, 2, 4, 6, 8]
Выберем только те ключи из словаря, длина которых больше 3:
dictionary = words = [f": " for key in dictionary if len(key) > 3] print(words) # ['blue: синий', 'green: зеленый']
Руководство по использованию list comprehension
У каждого языка программирования есть свои особенности и преимущества. Одна из культовых фишек Python — list comprehension (редко переводится на русский, но можно использовать определение «генератора списка»). Comprehension легко читать, и их используют как начинающие, так и опытные разработчики.
List comprehension — это упрощенный подход к созданию списка, который задействует цикл for, а также инструкции if-else для определения того, что в итоге окажется в финальном списке.
Преимущества list comprehension
У list comprehension есть три основных преимущества.
- Простота. List comprehension позволяют избавиться от циклов for, а также делают код более понятным. В JavaScript, например, есть нечто похожее в виде map() и filter() , но новичками они воспринимаются сложнее.
- Скорость. List comprehension быстрее for-циклов, которые он и заменяет. Это один из первых пунктов при рефакторинге Python-кода.
- Принципы функционального программирования. Это не так важно для начинающих, но функциональное программирование — это подход, при котором изменяемые данные не меняются. Поскольку list comprehensions создают новый список, не меняя существующий, их можно отнести к функциональному программированию.
Создание первого list comprehension
List comprehension записывается в квадратных скобках и задействует цикл for. В процессе создается новый список, куда добавляются все элементы оригинального. По мере добавления элементов их можно изменять.
Для начала возьмем простейший пример: создадим список из цифр от 1 до 5, используя функцию range() .
Python ‘if…else’ in a List Comprehension (Examples)
You can place an if. else statement into a list comprehension in Python.
["EVEN" if n % 2 == 0 else "ODD" for n in numbers]
Notice that the if. else statement in the above expression is not traditional if. else statement, though. Instead, it’s a ternary conditional operator, also known as the one-line if-else statement in Python.
Example
Given a list of numbers, let’s construct a list of strings that are odd/even based on what the corresponding number in the list of numbers is.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Use a list comprehension to create a new list that includes # "EVEN" for even numbers and "ODD" for odd numbers even_or_odd = ["EVEN" if n % 2 == 0 else "ODD" for n in numbers] print(even_or_odd) # Output: ["ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN"]
In this example, the if..else clause in the list comprehension checks to see if the number n is even (that is, if n is divisible by 2 with no remainder). If it is, the string “EVEN” is included in the new list; otherwise, the string “ODD” is included.
The Traditional Approach
Let’s see the traditional for loop with an if. else statement approach for comparison:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Create an empty list to store the results even_or_odd = [] # Use a for loop to iterate over the numbers for n in numbers: # Use an if..else statement to determine if the number is even or odd if n % 2 == 0: even_or_odd.append("EVEN") else: even_or_odd.append("ODD") print(even_or_odd) # Output: ["ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN"]
Here’s a fun little illustration of converting the traditional approach to a list comprehension with an if…else statement:
One-Line If-Else Statements in Python
To add an if. else statement into a list comprehension in Python, you need to use a slightly modified version of an if. else statement, called the conditional operator.
The conditional operator in Python allows you to write conditional expressions in a shorter and more concise way. It is also known as the ternary operator because it takes three operands.
Here is the general syntax for using the conditional operator in Python:
Here, x and y are the values that will be returned based on the evaluation of the condition . If the condition evaluates to True , x will be returned; otherwise, y will be returned.
Here is an example of using the conditional operator to return the maximum of two numbers:
# Define two numbers x = 5 y = 10 # Use the conditional operator to return the maximum of x and y max = x if x > y else y # Print the maximum print(max) # Output: 10
The condition checks to see if x is greater than y . If it is, the value of x is returned; otherwise, it returns y .
The conditional operator can be useful whenever you want to write a conditional expression in a single line of code. It can make your code more readable and concise by avoiding multi-line if..else statements. Also, some argue it only makes the code shorter but less readable which is why some don’t use conditional operators at all.
To include an if. else statement into a list comprehension, you need to pass it as a conditional expression.
Example
Let’s take a look at another example of list comprehensions an if. else statements.
Here is an example of a for loop with an if. else statement that prints whether a number is odd or even in a list of numbers.
First, let’s start with the traditional approach:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for number in numbers: if number % 2 == 0: print(number, "is even") else: print(number, "is odd")
1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 10 is even
This for loop can be converted into a one-line list comprehension expression using a conditional operator if. else :
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print([f" is " for number in numbers])
The output of this expression would be the same as the original for loop:
1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 10 is even
Should You Place If…Else Statements in List Comprehensions?
Whether or not you should use list comprehension expressions with conditional operators in your code depends on your personal preferences and the specific requirements of your project.
Some developers never use one-liner shorthand like list comprehensions or conditional operators.
List comprehensions can be a concise and elegant way to write certain types of for loops, but they can also make your code more difficult to read and understand if you are not familiar with the syntax.
If you are working on a small project with no collaborators, using list comprehension expressions (with if. else statements) can make your code more concise and easier to write.
However, if you are working on a larger project and you are collaborating with other people on a project, it may be more beneficial to use longer and more descriptive for loops that are easier for other people to read and understand.
Ultimately, the decision to use list comprehension in your code should be based on the specific needs of your project, the level of experience and familiarity of the people working on the project, and the trade-off between conciseness and readability.
My personal take: A list comprehension with an if. else statement looks messy and I’d probably not use such expression ever in my code.
Thanks for reading. Happy coding!