Intermediate Python Nanodegree - Representing Data
- 노트필기
- 2021. 5. 19.
[스터디 노트] Udacity - Intermediate Python Nanodegree
2. Advanced Python Techniques
Lesson 2. Representing Data
Representing Data
어떻게 데이터를 표시할지에 대한 고민이 필요함.
Variables and Namespaces
복사하면 객체를 복사하는 것이 아니라 Namespace 안에서 Reference를 추가하는 것.
== : comparing value
is : comparing identity
# == : comparing value
# is : comparing identity
print(1 == 1.0) # True
print(1 is 1.0) # False
print(id(1))
print(id(1.0))
#결과
#140737029482272
#1964061401840
print(id(41))
print(hex(id(41))) # -> memory address
#결과
#140737029483552
#0x7fffe4a62c20
Lists and Tuples
List Methods
# Extend list by appending elements from the iterable
my_list.extend(iterable)
# Insert object before index
my_list.insert(index, object)
# Remove first occurrence of value, or raise ValueError
my_list.remove(value)
# Remove all items
my_list.clear()
# Return number of occurrences of value
my_list.count(value)
# Return first index of value, or raise ValueError
my_list.index(value, [start, [stop]])
# Remove, return item at index (def. last) or IndexError
my_list.pop([index])
# Stable sort *in place*
my_list.sort(key=None, reverse=False)
# Reverse *in place*.
my_list.reverse()
Tuple Unpacking
first, *rest = 1, 2, 3, 4, 5
print(first) # => 1
print(rest) # => [2, 3, 4, 5]
Enumerate 사용하기
이거 사용하면 for i in range(len(sequence)) 필요 없음.
Comparing Sequence Types
Sized
Any object that is Sized can be used with the len function, which returns the number of items in a container. For example:
len("ABC") # => 3
len((1, 2, 4, 8)) # => 4
len(["do", "re", "mi", "fa", "so"]) # => 5
Container
Any object that is a Container can be used in the expression element in container. For example:
'd' in 'Udacity' # => True
12 in [5, 12, 13] # => True
(3, 4, 5) in ((3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25)) # => True
Iterable
Any object that is an Iterable knows how to produce its elements one at a time in a stream. An extraordinary number of built-in functions consume or produce iterables. For example, if we had an iterable named iterable or an iterable of iterables named iterables, we could run:
max(iterable)
min(iterable)
val in iterable
val not in iterable
all(iterable)
any(iterable)
# Produce iterables.
zip(*iterables)
enumerate(iterable)
filter(pred, iterable)
map(fn, iterable)
Dictionaries
Get with Default
In some cases, you'll want to either get the value associated with a key, or a default value if it's missing, rather than raising a KeyError. In these cases, you can use dict.get:
Key가 있는지 없는지 확인할 때는 get을 쓰면 된다. -> 없으면 default 값 리턴
temps = {'CA': [101, 115, 108], 'NY': [98, 102]}
temps['California'] # Raises an error (KeyError)!
temps.get('CA') # => [101, 115, 108]
temps.get('KY') # => None (not a KeyError!)
ky_temps = temps.get('KY', [])
num_observations = len(ky_temps)
Removing Elements
d = {"one": 1, "two": 2, "three": 3}
# Raises a KeyError if the key is missing.
del d["one"]
# Remove and return `d['three']`, or the default value if 'three' is not in the map.
d.pop("three", default) # => 3
# Remove and return an arbitrary (key, value) pair. Useful for destructive iteration.
d.popitem() # => ("two", 2)
Views
d = {"one": 1, "two": 2, "three": 3}
d.keys()
d.values()
d.items()
len(d.keys()) # => 3
('one', 1) in d.items() # => True
for value in d.values():
print(value) # Prints 1, 2, and 3
keys_list = list(d.keys()) # Create a new list, decoupled from the changes to the original dict.
for key, value in mydict.items():
do_something_with(key, value)
Sets
A set is an unordered collection of distinct hashable elements.
Sets are often used for:
- Efficiently checking if an element is contained in a collection.
- Eliminating duplicate entries from a collection.
- Representing abstract sets, with access to mathematical operators such as intersection and union.
Creating Set
empty_set = set()
set_from_list = set([1, 2, 3, 2, 3, 4, 3, 1, 2]) # => {1, 2, 3, 4}
그냥 {} 하면 Dictonary가 생성됨.
Set Operation
a = set("mississippi") # {'i', 'm', 'p', 's'}
a.add('r')
a.remove('m') # Raises a KeyError if 'm' is not present.
a.discard('x') # Same as `remove`, except won't raise an error.
a.pop() # => 's' (or 'i' or 'p')
a.clear()
len(a) # => 0
Mathmatical Set Operation
a = set("abracadabra") # {'a', 'b', 'c', 'd', 'r'}
b = set("alacazam") # {'a', 'm', 'c', 'l', 'z'}
# Set difference
a - b # => {'b', 'd', 'r'}
# Union
a | b # => {'a', 'b', 'c', 'd', 'l', 'm', 'r', 'z'}
# Intersection
a & b # => {'a', 'c'}
# Symmetric Difference
a ^ b # => {'b', 'd', 'l', 'm', 'r', 'z'}
# Subset
a <= b # => False
There are also named versions of these functions: set.difference, set.union, set.intersection, set.symmetric_difference, and set.issubset, as well as in-place versions set.difference_update, set.update, set.intersection_update, and set.symmetric_difference_update, corresponding to the operators -=, |=, &=, and ^=.
Comprehensions
Examples
# Lowercased versions of words in a sentence.
[word.lower() for word in sentence]
# Words in a sentence of more than 8 letters long.
[word for word in sentence if len(word) > 8]
# 3-tuples of the first ten numbers and their squares and cubes.
[(x, x ** 2, x ** 3) for x in range(10)]
# Indices for a triangular matrix.
[(i,j) for i in range(5) for j in range(i)]
Dictionary comprehensions
return {v: k for k, v in d.items()}
{student: grades for student, grades in gradebook.items() if sum(grades) / len(grades) > 90
Set comprehensions
{word for word in hamlet if is_palindrome(word.lower())}