You will study the basic grammar of Python 3 by referring to "Introduction to Python 3" by O'Reilly Japan. I hope it will be helpful for those who want to study Python in the same way.
Comprehension is a format that allows you to compactly create a Python data structure from one or more iterators.
The simplest form of list comprehension is as follows.
[ expression for item in iterable ]
--Normal (not included) code
>>> str_list = []
>>> for i in range(1, 6):
... str_list.append(str(i) * i)
...
>>> str_list
['1', '22', '333', '4444', '55555']
--Code in list comprehension
>>> [str(i) * i for i in range(1, 6)]
['1', '22', '333', '4444', '55555']
--Normal (not included) code
>>> num_list = []
>>> for i in range(1, 6):
... if i % 2 == 1:
... num_list.append(str(i) * i)
...
>>> num_list
['1', '333', '55555']
--Code in list comprehension
>>> [str(i) * i for i in range(1, 6) if i % 2 == 1]
['1', '333', '55555']
--Normal (not included) code
>>> keys = range(0, 3)
>>> vals = range(0, 3)
>>> for key in keys:
... for val in vals:
... print(key, val)
...
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
--Code in list comprehension
>>> keys = range(0, 3)
>>> vals = range(0, 3)
>>> tuple = [(key, val) for key in keys for val in vals]
>>> for key, val in tuple:
... print(key, val)
...
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
The simplest form of dictionary comprehension is as follows.
{ key_item : value_item for item in iterable }
>>> iter_obj = [(1, 'AA'), (2, 'BB'), (3, 'CC')]
>>> dict_obj = {key : val for key, val in iter_obj}
>>> dict_obj
{1: 'AA', 2: 'BB', 3: 'CC'}
The simplest form of set comprehension is as follows.
{ item for item in iterable }
>>> {10**i for i in range(1, 6)}
{100000, 100, 1000, 10, 10000}
The generator can only be run once.
>>> #What's between the parentheses is the generator comprehension, which returns the generator object.
>>> gene_obj = (num**2 for num in range(1, 6))
>>> num_list = list(gene_obj)
>>> num_list
[1, 4, 9, 16, 25]
>>> #When I use the same generator object again, nothing comes out
>>> num_list = list(gene_obj)
>>> num_list
[]
Recommended Posts