--Python has a large standard library of modules that do a lot of "useful work".
--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
>>> 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})
--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"),
... ])
>>>
--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
--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!')])
zop.py
def hours():
print("Open 9-5 daily")
result
>>> import zoo
>>> zoo.hours()
Open 9-5 daily
#Import module zoo as menagerie
>>> import zoo as menagerie
>>> menagerie.hours()
Open 9-5 daily
>>> from zoo import hours
>>> hours()
Open 9-5 daily
>>> from zoo import hours as info
>>> info()
Open 9-5 daily
>>> plain={"a":1,"b":2,"c":3}
>>> plain
{'a': 1, 'b': 2, 'c': 3}
>>> from collections import OrderedDict
>>> fancy=OrderedDict([("a",1),("b",2),("c",3)])
>>> fancy
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> from collections import defaultdict
>>> dict_of_lists=defaultdict(list)
>>> dict_of_lists["a"]=["something for a"]
>>> dict_of_lists["a"]
['something for a']
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.
"Introduction to Python3 by Bill Lubanovic (published by O'Reilly Japan)"
Recommended Posts