The other day I learned about 100 Days Of Code, which was popular on Twitter for a while. The purpose of this article is to keep a record and output how much I, as a beginner, can grow through 100 days of study. I think there are many mistakes and difficult to read. I would appreciate it if you could point out!
--Progress: Pages 15-28 ――I will write down what I often forget or didn't know about what I learned today.
In the case of comprehensions, a large amount of input may consume too much memory and cause the program to crash. So we use a generator formula. The generator expression does not actually generate the entire output sequence at run time. Instead, the iterator yields elements one by one from the expression.
List comprehension
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
value = [x**2 for x in a]
print(value)
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
#generator
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
iter= (x**2 for x in a) # "[]"To"()"Just change to
print(iter)
# <generator object <genexpr> at 0x0000025397AFBD48>
The returned iterator can be output step by step using the built-in function next.
print(next(iter))
print(next(iter))
for x in iter:
print(x)
Execution result
1
4
9
16
36
49
64
81
In the list below, consider the element with the largest number of characters and the program that outputs that number of characters. In this case, the code is easier to read if you zip it than if you enumerate it.
names = ['ABC', 'DEF123','GHIJK']
letters = [len(n) for n in names]
When using enumerate
longest_name = None
max_letters = 0
for i, name in enumerate(names):
count = letters[i]
if count > max_letters:
longest_name = name
max_letters = count
Using zip makes the code much easier to read.
longest_name = None
max_letters = 0
for name, count in zip(names, letters):
if count > max_letters:
longest_name = name
max_letters = count
Note that the zip behaves strangely if the number of input elements is different.
In python you can put an else block after the loop. The else block is not executed if the loop is not completed, but is ** executed when the loop is completed.
#The else block is executed after the loop is completed
for i in [0, 1, 2]:
print("Loop %d" % i)
else:
print("Else block")
Execution result
Loop 0
Loop 1
Loop 2
Else block
#The else block will not execute until the loop is complete
for i in [0, 1, 2]:
if i == 2:
break
print("Loop %d" % i)
else:
print("Else block")
** Do not use the else block immediately after the loop as the behavior is misleading **
By using try/finally when you want to perform cleanup processing when an exception occurs, you can reliably close the file.
handle = open('hoge.txt')
try:
data = handle.read()
finally:
handle.close() # try:Always executed after
You can use try/except/else to clarify the exception that is transmitted above and the exception that is caught by except. If the data does not come out in the correct json format, raise a ValueError in json.loads and it will be caught as except. If an exception occurs when comparing key values in the else block, it is propagated to the caller because it is outside the try block.
def load_json_key(data, key):
try:
result_dict = json.loads(data) #Value Error may occur
except ValueError as e:
raise KeyError from e
else:
return result_dict[key] #KeyError may occur
Recommended Posts