・ Because Qiita's comment mentioned the intensional expression, and I thought it was an opportunity to understand it now. (I've heard the comprehension itself in the "Python Tutorial", but it seemed difficult and I ran away. Now is my chance!)
The grammar itself doesn't seem to be as difficult as it looks. (I ran away because I thought it would be difficult ... sweat)
[Processing content for x in list etc.]
Personally, when I disassembled it as follows, I personally felt comfortable.
After "for", the form is the same as a normal Python for statement. Impression that the processing content is like a for statement that came before.
Code that triples each element
naiho.py
num_list = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
naiho = [x * 3 for x in num_list]
print(naiho)
Or a code to put the last name in the name
kawaii.py
gotobun = ["ithika", "nino", "miku", "yotsuba", "itsuki"]
hanayome = ["nakano " + z for z in gotobun]
print(hanayome)
Calculation can be done normally
[-12, -9, -6, -3, 0, 3, 6, 9, 12]
It's easy to create a string. It seems that there are many situations that can be used if devised.
['nakano ithika', 'nakano nino', 'nakano miku', 'nakano yotsuba', 'nakano itsuki']
If you try to process the above two sample codes with a for statement, it will look like the following.
no_naiho.py
num_list = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
not_naiho = []
for y in num_list:
y *= 3
not_naiho.append(y)
print(not_naiho)
no_kawaii.py
gotobun = ["ithika", "nino", "miku", "yotsuba", "itsuki"]
hanayome = []
for a in gotobun:
a = "nakano " + a
hanayome.append(a)
print(hanayome)
It doesn't change depending on whether it is included or not, but I will write it for the time being.
[-12, -9, -6, -3, 0, 3, 6, 9, 12]
['nakano ithika', 'nakano nino', 'nakano miku', 'nakano yotsuba', 'nakano itsuki']
・ I felt that by using the comprehension notation, I could write the for statement more simply than I expected. ・ If you are not familiar with the comprehension notation, write the for and below first, and then write the processing content at the end. I thought I would be less confused.
Recommended Posts