Effective Python Learning Memorandum Day 2 [2/100]

Introduction

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!

Teaching materials to be learned this time

Today's progress

--Progress: Pages 15-28 ――I will write down what I often forget or didn't know about what I learned today.

Consider generator expressions for large comprehensions

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

Use zip to process iterators in parallel

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.

About the else block after the for and while loops

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 **

try/finally block

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

tyr/except/else block

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

Effective Python Learning Memorandum Day 15 [15/100]
Effective Python Learning Memorandum Day 6 [6/100]
Effective Python Learning Memorandum Day 12 [12/100]
Effective Python Learning Memorandum Day 14 [14/100]
Effective Python Learning Memorandum Day 13 [13/100]
Effective Python Learning Memorandum Day 3 [3/100]
Effective Python Learning Memorandum Day 5 [5/100]
Effective Python Learning Memorandum Day 4 [4/100]
Effective Python Learning Memorandum Day 7 [7/100]
Effective Python Learning Memorandum Day 2 [2/100]
Python learning day 4
Python memorandum
Python Memorandum 2
Python memorandum
python learning
python memorandum
python memorandum
Python day 1
Python memorandum
python memorandum
Python memorandum
Python basics memorandum
[Python] Learning Note 1
Python learning notes
Python memorandum (algorithm)
python learning output
Deep Learning Memorandum
Python learning site
Python Deep Learning
Python learning (supplement)
Deep learning × Python
Python memorandum [links]
python learning notes
Python study day 1
Machine learning starting with Python Personal memorandum Part2
Machine learning starting with Python Personal memorandum Part1
Python memorandum numbering variables
Python class (Python learning memo ⑦)
Learning Python with ChemTHEATER 03
"Object-oriented" learning with python
Python module (Python learning memo ④)
Reinforcement learning 1 Python installation
Learning Python with ChemTHEATER 05-1
Python: Deep Learning Practices
python memorandum (sequential update)
Python: Unsupervised Learning: Basics
Learning record 4 (8th day)
Learning record 9 (13th day)
[1day1lang AdventCalender] day4 Python
Learning record 3 (7th day)
Learning record 5 (9th day)
Learning record 6 (10th day)
Python memorandum (personal bookmark)
Programming learning record day 2
Learning record 8 (12th day)
Learning record 1 (4th day)
Learning record 7 (11th day)
Private Python learning procedure
Learning Python with ChemTHEATER 02
Python basic memorandum part 2
Learning record 2 (6th day)