[Introduction to Python3 Day 10] Chapter 5 Py's Cosmetic Box: Modules, Packages, Programs (5.4-5.7)

5.5 Python standard library

--Python has a large standard library of modules that do a lot of "useful work".

5.5.1 Handling non-existent keys with setdefault () and defaultdict ()

--An exception is generated when trying to access the dictionary with a key that does not exist. You can avoid exceptions by using the dictionary get () function to return the default value if the key does not exist. --The setdefault () function is similar to get (), except that it adds more elements to the dictionary if it doesn't have a key. --The defaultdict () function differs from get () in that it sets default values for all nonexistent keys. ** The argument is a function. ** Also, if you use a key that does not exist, that key will be generated automatically. Default value If you omit the argument, the default value is None.


>>> periodic_table={"Hydrogen":1,"Helium":2}
>>> print(periodic_table)
{'Hydrogen': 1, 'Helium': 2}
#If the key is not in the dictionary, it will be added with the new value.
>>> carbon=periodic_table.setdefault("Carbon",12)
>>> carbon
12
#Attempting to assign another default value to an existing key will return the original value and will not change the dictionary.
>>> helium=periodic_table.setdefault("Helium",457)
>>> helium
2
>>> print(periodic_table)
{'Hydrogen': 1, 'Helium': 2, 'Carbon': 12}


#Import defaultdict from module collections.
>>> from collections import defaultdict
#Default value for non-existent keys(int)Is set.
>>> periodic_table=defaultdict(int)
>>> periodic_table["Hydrogen"]=1
#A default value is returned for a key that does not exist.
>>> periodic_table["Lead"]
0
>>> periodic_table
defaultdict(<class 'int'>, {'Hydrogen': 1, 'Lead': 0})


#Import defaultdict from module collections
>>> from collections import defaultdict
>>> 
>>> def no_idea():
...     return "Huh?"
... 
>>> bestiary = defaultdict(no_idea)
>>> bestiary["a"]= "A"
>>> bestiary["b"]= "B"
>>> bestiary["a"]
'A'
>>> bestiary["b"]
'B'

#If you enter a key that does not exist, the function specified by the argument of defaultdict is called and the value is returned.
>>> bestiary["c"]
'Huh?'
>>> bestiary["v"]
'Huh?'

#defaultdict()Define default creation function in call
>>> bestiary=defaultdict(lambda:"Huh?")
>>> bestiary["E"]
'Huh?'

#ints can be a way to create your own counters.
>>> from collections import defaultdict
>>> food_counter=defaultdict(int)
>>> for food in ["spam","spam","eggs","spam"]:
...     food_counter[food]+=1
... 
>>> for food,count in food_counter.items():
...     print(food,count)
... 
spam 3
eggs 1

5.5.2 Calculation of the number of elements by Counter ()


>>> breakfast=["spam","spam","eggs","spam"]
>>> breakfast_counter=Counter(breakfast)
>>> breakfast_counter
Counter({'spam': 3, 'eggs': 1})
#most_common()The function returns all elements in descending order.
>>> breakfast_counter.most_common()
[('spam', 3), ('eggs', 1)]
#most_common()If an integer is specified as an argument, the function counts from the top and displays the number.
>>> breakfast_counter.most_common(1)
[('spam', 3)]
>>> breakfast_counter
Counter({'spam': 3, 'eggs': 1})

>>> lunch=["eggs","eggs","bacon"]
>>> lunch_counter=Counter(lunch)
>>> lunch_counter
Counter({'eggs': 2, 'bacon': 1})
#Counter coupling
>>> lunch_counter+breakfast_counter
Counter({'eggs': 3, 'spam': 3, 'bacon': 1})
#Counter difference Items that are used for lunch but not for breakfast.
>>> lunch_counter-breakfast_counter
Counter({'eggs': 1, 'bacon': 1})
#Counter difference What is used at breakfast but not at lunch.
>>> breakfast_counter-lunch_counter
Counter({'spam': 3})
#The intersection operator is 1.
>>> breakfast_counter & lunch_counter
Counter({'eggs': 1})
#Union operator Uses the larger counter value.
>>> breakfast_counter | lunch_counter
Counter({'spam': 3, 'eggs': 2, 'bacon': 1})

5.5.3 Key order sorting by OrderdDict ()

--OrderedDict () returns the keys from the iterator in the same order.


>>> quotes={
...     "M":"A",
...     "L":"O",
...     "C":"N",
...     }
>>> for s in quotes:
...     print(s)
... 
M
L
C

>>> from collections import OrderedDict
>>> quotes=OrderedDict([
...     ("M","A"),
...     ("L","C"),
...     ("C","N"),
...     ])
>>> 

5.5.4 Stack + Queue = Deck

--Duke is a deque, which has both stack and queue functions, and you can add or remove elements at either end of the sequence.


>>> def palindrome(word):
...     from collections import deque
...     dq=deque(word)
...     while len(dq)>1:
#popleft()Deletes the leftmost element and returns, pop()Is a function that deletes the rightmost element and returns it.
...         if dq.popleft()!=dq.pop():
...             return False
...     return True
... 
>>> palindrome("a")
True
>>> palindrome(" ")
True
>>> palindrome("racecar")
True
>>> palindrome("halibut")
False

#It's easier to compare strings in reverse order.
>>> def another_palindrome(word):
...     return word==word[::-1]
... 
>>> another_palindrome("racecar")
True
>>> another_palindrome("halibut")
False

5.5.5 Iterating code structure with itertools

--itertools contains iterator functions with special purposes.


#chain()Treats the entire argument as if it were one iterable, and iterates through it.
>>> import itertools
>>> for item in itertools.chain([1,2],["a","b"]):
...     print(item)
... 
1
2
a
b

#cycle()Is an infinite iterator that returns elements cyclically from its arguments.
>>> import itertools
>>> for item in itertools.cycle([1,2]):
...     print(item)
... 
1
2
1
2
1
2
1
2
1
2
1
2
1
2

#accumulate()Calculates the value of the elements combined into one. The default is to calculate the sum.
>>> import itertools
>>> for item in itertools.accumulate([1,2,3,4]):
...     print(item)
... 
1
3
6
10

##accumulate()Accepts a function as the second argument, and this argument is used instead of addition.
>>> import itertools
>>> def multiply(a,b):
...     return a*b
... 
>>> for item in itertools.accumulate([1,2,3,4],multiply):
...     print(item)
... 
1
2
6
24

5.5.6 Beautiful display by pprint ()

--print () tries to align the elements for readability.


>>> from pprint import pprint
>>> q=OrderedDict([
...     ("Moe","A wise guy,huh?"),
...     ("Larry","Ow!"),
...     ("Curly","Nuyk nyuk!"),
...     ])
>>> 
#Continue to display.
>>> print(q)
OrderedDict([('Moe', 'A wise guy,huh?'), ('Larry', 'Ow!'), ('Curly', 'Nuyk nyuk!')])

#Align and display the elements.
>>> pprint(q)
OrderedDict([('Moe', 'A wise guy,huh?'),
             ('Larry', 'Ow!'),
             ('Curly', 'Nuyk nyuk!')])


5.7 Review assignment

5-1 Create a file called zoo.py and display the character string Open 9-5 daily in it. Let's define the hours () function. Next, let's import the zoo module with the interactive interpreter and call its hours () function.

zop.py



def hours():
    print("Open 9-5 daily")

result



>>> import zoo
>>> zoo.hours()
Open 9-5 daily

5-2 Import the zoo module with the name menagerie in the interactive interpreter and call its hours () function.


#Import module zoo as menagerie
>>> import zoo as menagerie
>>> menagerie.hours()
Open 9-5 daily

5-3 Let's stay in the interactive interpreter and directly import and call the hours () function of zoo.


>>> from zoo import hours
>>> hours()
Open 9-5 daily

5-4 hours () Import the function with the name info and call it.


>>> from zoo import hours as info
>>> info()
Open 9-5 daily

5-5 Create a dictionary called plain using the key / value pairs "a": 1, "b": 2, "c": 3 and display the contents.


>>> plain={"a":1,"b":2,"c":3}
>>> plain
{'a': 1, 'b': 2, 'c': 3}

5-6 Create an OrderedDict named fancy from the same pair as 5-5 above and display its contents. Was it displayed in the same order as plain?


>>> from collections import OrderedDict
>>> fancy=OrderedDict([("a",1),("b",2),("c",3)])
>>> fancy
OrderedDict([('a', 1), ('b', 2), ('c', 3)])


5-7 Create a defaultdict named dict_of_lists and pass the list argument. Next, create a list called dict_of_lists ["a"] in one operation and add the value "something for a". Finally, let's display dict_of_lists ["a"].


>>> from collections import defaultdict
>>> dict_of_lists=defaultdict(list)
>>> dict_of_lists["a"]=["something for a"]
>>> dict_of_lists["a"]
['something for a']

Impressions

Finally, we have entered the second half of the game. I started doing Chapter 6, but the concept of objects and classes came out. I will continue to do my best tomorrow.

References

"Introduction to Python3 by Bill Lubanovic (published by O'Reilly Japan)"

Recommended Posts

[Introduction to Python3 Day 10] Chapter 5 Py's Cosmetic Box: Modules, Packages, Programs (5.4-5.7)
[Introduction to Python3 Day 9] Chapter 5 Py's Cosmetic Box: Modules, Packages, Programs (5.1-5.4)
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[Introduction to Python3 Day 14] Chapter 7 Strings (7.1.1.1 to 7.1.1.4)
[Introduction to Python3 Day 15] Chapter 7 Strings (7.1.2-7.1.2.2)
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Python3 Day 18] Chapter 8 Data Destinations (8.3.6.2 to 8.3.6.3)
[Introduction to Python3 Day 12] Chapter 6 Objects and Classes (6.3-6.15)
[Introduction to Python3 Day 22] Chapter 11 Concurrency and Networking (11.1 to 11.3)
[Introduction to Python3 Day 11] Chapter 6 Objects and Classes (6.1-6.2)
[Introduction to Python3 Day 23] Chapter 12 Become a Paisonista (12.1 to 12.6)
[Introduction to Python3 Day 20] Chapter 9 Unraveling the Web (9.1-9.4)
[Introduction to Python3 Day 8] Chapter 4 Py Skin: Code Structure (4.1-4.13)
[Introduction to Python3 Day 3] Chapter 2 Py components: Numbers, strings, variables (2.2-2.3.6)
[Introduction to Python3 Day 2] Chapter 2 Py Components: Numbers, Strings, Variables (2.1)
[Introduction to Python3 Day 4] Chapter 2 Py Components: Numbers, Strings, Variables (2.3.7-2.4)
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python3 Day 7] Chapter 3 Py Tools: Lists, Tuples, Dictionaries, Sets (3.3-3.8)
[Introduction to Python3 Day 5] Chapter 3 Py Tools: Lists, Tuples, Dictionaries, Sets (3.1-3.2.6)
[Introduction to Python3 Day 6] Chapter 3 Py tool lists, tuples, dictionaries, sets (3.2.7-3.2.19)
Introduction to Effectiveness Verification Chapter 1 in Python
Introduction to effectiveness verification Chapter 3 written in Python
Introduction to Effectiveness Verification Chapter 2 Written in Python
Understand Python for Pepper development. -Introduction to Python Box-
Python packages and modules
[Chapter 5] Introduction to Python with 100 knocks of language processing
Introduction to Python language
Introduction to OpenCV (python)-(2)
[Chapter 3] Introduction to Python with 100 knocks of language processing
[Chapter 2] Introduction to Python with 100 knocks of language processing
[Technical book] Introduction to data analysis using Python -1 Chapter Introduction-
[Chapter 4] Introduction to Python with 100 knocks of language processing
Introduction to electronic paper modules
Understand Python packages and modules
Introduction to serial communication [Python]
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)
An introduction to Python Programming
Introduction to Python For, While
Python learning memo for machine learning by Chainer Chapter 8 Introduction to Numpy
Python learning memo for machine learning by Chainer Chapter 10 Introduction to Cupy
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 1
Python learning memo for machine learning by Chainer Chapter 9 Introduction to scikit-learn
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 2
[Introduction to Udemy Python 3 + Application] 58. Lambda
[Introduction to Udemy Python 3 + Application] 31. Comments
Introduction to Python Numerical Library NumPy
Practice! !! Introduction to Python (Type Hints)
[Introduction to Python] <numpy ndarray> [edit: 2020/02/22]
[Introduction to Udemy Python 3 + Application] 57. Decorator
Introduction to Python Hands On Part 1
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
Introduction to Protobuf-c (C language ⇔ Python)
[Introduction to Udemy Python3 + Application] 59. Generator
Python Basic Course (14 Modules and Packages)
[Introduction to Python] Let's use pandas
[Introduction to Python] Let's use pandas
[Introduction to Udemy Python 3 + Application] Summary
Introduction to image analysis opencv python