Comprehension notation allows you to write list, set, and dictionary data operations in a short number of lines. It also speeds up processing, so use this if you have a huge number of elements.
First, execute the program that uses the following list comprehension notation.
list_comprehension1.py
result = [x**2 for x in [1, 2, 3, 4, 5]]
print("{0}".format(result))
x ** 2 means "x squared", and the list result contains the following values:
[1, 4, 9, 16, 25]
If you don't use list comprehensions, you can replace the above program with:
list_comprehension2.py
result = []
for i in [1, 2, 3, 4, 5]:
result.append(i**2)
print("{0}".format(result))
** [** * Values to put in elements (using variables) * ** for ** * Variables * ** in ** * List * **] **
Lists can use list-type data like programs, and range () can also be used like range (1,6).
In list comprehension notation, you can specify the elements to be processed and the elements not to be processed in the elements of the list.
list_comprehension3.py
print("{0}".format( [x*10+1 for x in range(1,6) if x > 2 and x < 5]))
The output result is as follows.
[31, 41]
Since the list comprehension returns a list, it is of course possible to give the list comprehension directly to the print statement. If you don't use list comprehensions, you can replace the above program with:
list_comprehension4.py
result = []
for x in range(1,6):
if x > 2 and x < 5:
result.append(x*10+1)
print("{0}".format(result))
** [** * Values to put in elements (using variables) * ** for ** * Variables * ** in ** * List * * Conditions * **] **
The inclusion notation can also be used as a set. The usage is the same as the list comprehension notation.
set_comprehension.py
print("{0}".format( {x*10+1 for x in range(1,6) if x > 2 and x < 5}))
The output result is as follows. set([41, 31])
Separating keys and values with: and enclosing keys: values with {} is the same as a normal dictionary. The usage is the same as the list.
dictionary_comprehension.py
print("{0}".format( {str(x):x**2 for x in range(1,6)}))
You can do the same thing without using comprehensions, but you can achieve simple and high-speed operation. A good source code will be created if you use it with the inclusion notation in mind.
Next: Python Basic Course (11 exceptions)
Recommended Posts