Udemy's course, Introduction to Python 3 taught by active Silicon Valley engineers + Applications + American Silicon Valley style code style It is a memo of.
It can store data of any type (integer, floating point number, string, etc.). The elements are in order and you can specify them using indexes. List elements can be changed . Use it like an "array" in other programming languages.
Determining if a person can get on a taxi seat
>>> seat = []
>>> min = 0
>>> max = 4
>>> min <= len(seat) < max
True
>>> seat.append("person")
>>> len(seat)
1
>>> seat.append("person")
>>> seat.append("person")
>>> seat.append("person")
>>> min <= len(seat) < max
False
>>> seat.pop(0)
"person"
It can store data of any type (integer, floating point number, string, etc.). The elements are in order and you can specify them using indexes. Unlike lists, tuple elements are immutable
quiz
>>> chose_from_two = ("A", "B", "C")
>>> answer = []
>>> answer.append("A")
>>> answer.append("C")
Stores data represented by key / value pairs. Elements have no order (elements cannot be specified by index). Corresponds to "associative array" in other programming languages
Fruit EC site
>>> fruits = {"apple": 100, "banana": 200, "orange": 300}
>>> fruits.items()
dict_items([('apple', 100), ('banana', 200), ('orange', 300)])
>>> fruits.keys()
dict_keys(['apple', 'banana', 'orange'])
>>> fruits.values()
dict_values([100, 200, 300])
>>> fruits["apple"]
100
>>> fruits.get("apple")
100
>>> fruits.pop("apple")
100
>>> "apple" in fruits
False
A type for handling "sets" in mathematics. Each element does not overlap and has no order (elements cannot be specified by index)
Find "common friends" on SNS
>>> my_friends = {"A", "C", "D"}
>>> A_friends = {"B", "D", "E", "F"}
>>> my_friends & A_friends
{'D'}
>>> fruits = ["apple", "banana", "apple", "banana"]
>>> kind = set(fruits)
>>> kind
{'apple', 'banana'}
>>> s = "fdjsafiewafjdsaeiwfdafke"
>>> d = {}
>>> for c in s:
... if c not in d:
... d[c] = 0
... d[c] += 1
>>> print(d)
{'f': 5, 'd': 3, 'j': 2, 's': 2, 'a': 4, 'i': 2, 'e': 3, 'w': 2, 'k': 1}
You can write the following using the setdefault
function
>>> s = "fdjsafiewafjdsaeiwfdafke"
>>> d = {}
>>> for c in s:
... d.setdefault(c, 0)
... d[c] += 1
>>> print(d)
{'f': 5, 'd': 3, 'j': 2, 's': 2, 'a': 4, 'i': 2, 'e': 3, 'w': 2, 'k': 1}
You don't have to call setdefault
every time you use the python standard library defaultdict
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for c in s:
... d[c] += 1
...
>>> print(d)
defaultdict(<class 'int'>, {'f': 5, 'd': 3, 'j': 2, 's': 2, 'a': 4, 'i': 2, 'e': 3, 'w': 2, 'k': 1})
Recommended Posts