📅  最后修改于: 2023-12-03 15:18:56.317000             🧑  作者: Mango
List comprehension is a powerful tool in Python that allows you to create lists in a concise and elegant way. In this tutorial, we will learn how to use list comprehension with double for loops.
The syntax of list comprehension with double for loops is as follows:
new_list = [expression1 for item1 in iterable1 for item2 in iterable2 if condition]
expression1
is the expression that is evaluated and added to the new list.item1
is the variable that takes the values from the first iterable.iterable1
is the first iterable that is iterated over.item2
is the variable that takes the values from the second iterable.iterable2
is the second iterable that is iterated over.condition
is an optional condition that filters the values.Let's first create a list of numbers from 0 to 9 using a for loop:
numbers = []
for i in range(10):
numbers.append(i)
print(numbers)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Now, let's create a list of squares of these numbers using list comprehension with double for loop:
squares = [i**2 for i in numbers]
print(squares)
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Let's create a list of pairs of numbers where the sum of the numbers is even:
pairs = [(i, j) for i in range(3) for j in range(3) if (i+j)%2 == 0]
print(pairs)
Output:
[(0, 0), (0, 2), (1, 1), (2, 0), (2, 2)]
In this example, we used nested for loops to iterate over the range of numbers and a condition to filter the pairs whose sum is even.
List comprehension with double for loops is a powerful tool in Python that allows you to create lists in a concise and elegant way. With this tutorial, you should be able to use list comprehension with double for loops in your Python projects.