There is a format called comprehension in python, I've been doing it without using it at all, but it's related to performance, so I thought I'd try to understand it properly.
Make a list of only odd numbers from 1 to 100. How to make without using comprehension is as follows
list1.py
list = []
for number in range(1,101):
if number % 2 ==1:
list.append(number)
print(list)
Next, I'll try the same thing using comprehensions. The program is as follows
list2.py
list = [number for number in range(1,101) if number %2 ==1]
print(list)
The first number will be the number stored in the list. The number after for is a part of the number for for.
Make a set of only odd numbers from 1 to 99. Call it in a comprehension like a list.
shugo.py
list = {number for number in range(1,101) if number %2 ==1}
print(list)
Similarly, dictionaries use comprehensions. A program that counts how many times the word character appears
jisyo.py
word = 'aiueokakiku'
word_count = {x:word.count(x) for x in word}
print(word_count)
Let's make it like a list.
tuple1.py
tuple = (number for number in range(1,101) if number %2 ==1)
print(tuple)
When you run
<generator object <genexpr> at 0x101435f61>
It's not an error, but the generator returns when I use ()
In other words, ** tuples have no inclusions **.
I will try if it is really fast. First, let's make a list of odd numbers from 1 to 10000000 without using comprehension.
test1.py
import time
start = time.time()
list = []
for number in range(1,10000001):
if number % 2 ==1:
list.append(number)
print("Execution time:{0}",time.time() - start)
The average of 5 runs was ** 1.71131701469 **
Next, I will try the same thing with the inclusion notation
test2.py
import time
start = time.time()
list = [number for number in range(1,10000001) if number %2 ==1]
print("Execution time:{0}",time.time() - start)
The average of 5 runs was ** 0.88413858413 **
Writing in comprehension is about twice as fast and simply reduces the amount of code. It seems that it will be easier to read as you get used to it, so I will do my best to get used to it as soon as possible.
Recommended Posts