행위

"Python Cheat Sheet"의 두 판 사이의 차이

DB CAFE

 
1번째 줄: 1번째 줄:
# Python Cheat Sheet
+
= Python Cheat Sheet =
  
 
Support/Big Data/Document/My Docs/Python/Python_CheatSheet.MD
 
Support/Big Data/Document/My Docs/Python/Python_CheatSheet.MD
  
## Installation/Config
+
== Installation/Config ==
  
### PIP
+
=== PIP ===
 +
 
 +
<source lang=bash>
  
```shell
 
 
-- list all installed packages
 
-- list all installed packages
 
pip list
 
pip list
19번째 줄: 20번째 줄:
 
-- show the package location
 
-- show the package location
 
pip show <packagename>
 
pip show <packagename>
 +
</source>
  
-- location of the globally installed packages
+
=== location of the globally installed packages ===
 +
<source lang=bash>
 
python -m site
 
python -m site
 +
</source>
  
 +
<source lang=python>
 
>>> import site
 
>>> import site
 
>>> print(site.getsitepackages())'
 
>>> print(site.getsitepackages())'
29번째 줄: 34번째 줄:
 
>>> import sys
 
>>> import sys
 
>>> sys.path
 
>>> sys.path
 +
</source>
  
-- location of the locally installed packages
+
=== location of the locally installed packages ===
 +
<source lang=sql>
 
pythom -m site --user-site
 
pythom -m site --user-site
--
+
</source>
```
+
 
  
## Virtual Env (Python 3.3+)
+
=== Virtual Env (Python 3.3+) ===
  
venv is a package shipped with Python 3, which you can run using python3 -m venv. It serves the same purpose as virtualenv, but only has a subset of its features. virtualenv continues to be more popular than venv, especially since the former supports both Python 2 and 3.
+
* venv is a package shipped with Python 3, which you can run using python3 -m venv.  
 +
* It serves the same purpose as virtualenv, but only has a subset of its features.  
 +
* virtualenv continues to be more popular than venv, especially since the former supports both Python 2 and 3.
  
 
[Difference between virtualenv and venv](https://virtualenv.pypa.io/en/latest/)
 
[Difference between virtualenv and venv](https://virtualenv.pypa.io/en/latest/)
  
### Install virtualenv
+
==== Install virtualenv ====
 
+
<source lang=bash>
```shell
 
 
pip install virtualenv
 
pip install virtualenv
 +
</source>
  
-- upgrade virtualenv
+
==== upgrade virtualenv ====
 +
<source lang=bash>
 
pip install --upgrade virtualenv
 
pip install --upgrade virtualenv
 +
</source>
  
-- using virtualenv to create a virtual env for a particular python version
+
==== using virtualenv to create a virtual env for a particular python version ====
 +
<source lang=sql>
 
virtualenv -p /usr/local/bin/python3.5 kevin-venv
 
virtualenv -p /usr/local/bin/python3.5 kevin-venv
```
+
</source>
 +
 
  
### Create a virtual env
+
=== Create a virtual env ===
  
```Shell
+
<source lang=sql>
 
python -m venv <venv-name>
 
python -m venv <venv-name>
  
 
python -m venv kevin-venv
 
python -m venv kevin-venv
 +
</source>
  
-- include global python packages
+
==== include global python packages ====
 +
<source lang=sql>
 
python -m venv kevin-venv --system-site-packages
 
python -m venv kevin-venv --system-site-packages
 +
</source>
  
-- using --local to list only local installed packages
+
=== using --local to list only local installed packages ===
 +
<source lang=sql>
 
pip list --local
 
pip list --local
  
72번째 줄: 89번째 줄:
 
>2a. python -m venv kevin_python_proj1/.venv
 
>2a. python -m venv kevin_python_proj1/.venv
 
>2b. cd mkdir kevin_python_proj1 && python -m venv .venv
 
>2b. cd mkdir kevin_python_proj1 && python -m venv .venv
 +
</source>
  
 
+
=== Activate/Deactivate the vtirual env ===
```
+
==== activate ====
 
+
<source lang=sql>
### Activate/Deactivate the vtirual env
 
 
 
```Shell
 
-- activate
 
 
source <venv-name>/bin/activate
 
source <venv-name>/bin/activate
 
source kevin-venv/bin/activate
 
source kevin-venv/bin/activate
 +
</source>
  
-- deactivate
+
==== deactivate ====
 +
<source lang=sql>
 
deactivate
 
deactivate
```
+
</source>
  
### Delete a virtualenv
 
  
```shell
+
=== Delete a virtualenv ===
 +
<source lang=bash>
 
rm -rf <venv-name>
 
rm -rf <venv-name>
 
rm -rf kevin-venv
 
rm -rf kevin-venv
```
+
</source>
 +
 
  
### Store copy of python package versions
+
=== Store copy of python package versions ===
  
```shell
+
<source lang=bash>
 
-- all packages
 
-- all packages
 
pip freeze > requirements.txt
 
pip freeze > requirements.txt
 +
 
-- only local installed packages
 
-- only local installed packages
 
pip freeze --local > requirements.txt
 
pip freeze --local > requirements.txt
```
+
</source>
 +
 
  
### Install all packages from requirements.txt
+
=== Install all packages from requirements.txt ===
  
```shell
+
<source lang=sql>
 
pip install -r requriments.txt
 
pip install -r requriments.txt
```
+
</source>
 +
 
  
## Tips and Tricks
+
== Tips and Tricks ==
  
### Date, Time, DateTime, Timezone
+
=== Date, Time, DateTime, Timezone ===
  
 
[See this](https://docs.python.org/3/library/datetime.html#datetime.datetime.now)
 
[See this](https://docs.python.org/3/library/datetime.html#datetime.datetime.now)
  
```python
+
<source lang=python>
 +
 
 
from datetime import datetime, date, time, timezone, timedelta
 
from datetime import datetime, date, time, timezone, timedelta
  
131번째 줄: 152번째 줄:
 
print("The local time is: ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()));
 
print("The local time is: ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()));
 
# The local time is:  2022-02-15 15:50:03
 
# The local time is:  2022-02-15 15:50:03
```
+
</source>
 +
 
 +
 
 +
=== switch value ===
  
### switch value
+
<source lang=python>
  
```python
 
 
a = 10
 
a = 10
 
b = 30
 
b = 30
141번째 줄: 164번째 줄:
 
# switch value, now a = 30, b = 10
 
# switch value, now a = 30, b = 10
 
a,b = b,a
 
a,b = b,a
```
+
</source>
 +
 
 +
 
 +
=== Merging Dictionaries (Python 3.5+) ===
  
### Merging Dictionaries (Python 3.5+)
+
<source lang=sql>
  
```python
 
 
x = {'a': 1, 'b': 2}
 
x = {'a': 1, 'b': 2}
 
y = {'c', 3, 'd': 4}
 
y = {'c', 3, 'd': 4}
158번째 줄: 183번째 줄:
 
# merged = {'a': 3, 'b': 2, 'c': 4}
 
# merged = {'a': 3, 'b': 2, 'c': 4}
 
merged = {**x, **y}
 
merged = {**x, **y}
```
+
</source>
  
### Check if a module contain a class/method
+
=== Check if a module contain a class/method ===
  
```python
+
<source lang=python>
  
 
# Using a list comprehension
 
# Using a list comprehension
176번째 줄: 201번째 줄:
  
 
help(collections.namedtuple)
 
help(collections.namedtuple)
```
+
</source>
  
 
## Comprehensions
 
## Comprehensions
  
### List Comprehensions
+
=== List Comprehensions ===
  
 
[expression for item in iterable]
 
[expression for item in iterable]
 
[expression for item in iterable if condition]
 
[expression for item in iterable if condition]
  
```python
+
<source lang=python>
 
squares = [x * x for x in range(10)]
 
squares = [x * x for x in range(10)]
  
195번째 줄: 220번째 줄:
 
matrix = [(x,y) for x in x_dimension for y in y_dimension]
 
matrix = [(x,y) for x in x_dimension for y in y_dimension]
 
#output: [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
 
#output: [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
```
+
</source>
  
### Tuple Comprehensions
+
=== Tuple Comprehensions ===
  
 
there is no such thing. there is no tuple comprehension
 
there is no such thing. there is no tuple comprehension
  
### Dictionary Comprehensions
+
=== Dictionary Comprehensions ===
  
 
{key_expression: value_expression for expression in iterable}
 
{key_expression: value_expression for expression in iterable}
  
```python
+
<source lang=python>
 
word = "dictionary"
 
word = "dictionary"
  
218번째 줄: 243번째 줄:
 
new_salary = {k: v*1.5 if v < 500 else v for (k, v) in old_salary.items()}
 
new_salary = {k: v*1.5 if v < 500 else v for (k, v) in old_salary.items()}
 
#output: new_salary = {'Kevin': 2000, 'Brandon': 600.0, 'Elena': 450.0}
 
#output: new_salary = {'Kevin': 2000, 'Brandon': 600.0, 'Elena': 450.0}
```
+
</source>
  
### Set Comprehensions
+
=== Set Comprehensions ===
  
 
{expression for item in iterable}
 
{expression for item in iterable}
 
{expression for item in iterable if condition}
 
{expression for item in iterable if condition}
  
```python
+
<source lang=python>
 
random_nums = [3, 6, 9, 3, 9, 18, 20, 18]
 
random_nums = [3, 6, 9, 3, 9, 18, 20, 18]
  
231번째 줄: 256번째 줄:
  
 
#output: {18, 20}
 
#output: {18, 20}
```
+
</source>
  
### Generator Comprehensions
+
=== Generator Comprehensions ===
  
```python
+
<source lang=python>
 
from pprint import pprint
 
from pprint import pprint
 
some_nums = (num for num in range(5))
 
some_nums = (num for num in range(5))
 
pprint(some_nums)
 
pprint(some_nums)
 
#output: <generator object <genexpr> at 0x00000264B87BCF90>
 
#output: <generator object <genexpr> at 0x00000264B87BCF90>
```
+
</source>
  
 
## Functional Programming
 
## Functional Programming
  
### Named Tuple
+
=== Named Tuple ===
  
```python
+
<source lang=python>
 
import collections
 
import collections
 
from pprint import pprint
 
from pprint import pprint
272번째 줄: 297번째 줄:
 
  Cruise(year=2017, cruise_line='NCL', ship='Escape', days=7),
 
  Cruise(year=2017, cruise_line='NCL', ship='Escape', days=7),
 
  Cruise(year=2018, cruise_line='NCL', ship='Bliss', days=7))
 
  Cruise(year=2018, cruise_line='NCL', ship='Bliss', days=7))
```
+
</source>
  
### Filter()
+
=== Filter() ===
  
```python
+
<source lang=python>
 
# Method A: print only RCL cruise: using filter
 
# Method A: print only RCL cruise: using filter
 
rcl_cruise = tuple(
 
rcl_cruise = tuple(
292번째 줄: 317번째 줄:
  
 
pprint(rcl_cruise2)
 
pprint(rcl_cruise2)
```
+
</source>
  
### Map Function
+
=== Map Function ===
  
```python
+
<source lang=python>
  
 
## Method A: using map function
 
## Method A: using map function
347번째 줄: 372번째 줄:
 
# defaultdict(<class 'list'>, {'RCL': [2016], 'NCL': [2017, 2018]})
 
# defaultdict(<class 'list'>, {'RCL': [2016], 'NCL': [2017, 2018]})
 
# please notice result doesn't have 'DISNEY' in it
 
# please notice result doesn't have 'DISNEY' in it
```
+
</source>
  
### Reduce Function
+
=== Reduce Function ===
  
```python
+
<source lang=python>
 
# Method A: using reduce() function
 
# Method A: using reduce() function
 
from functools import reduce
 
from functools import reduce
361번째 줄: 386번째 줄:
 
# Method B: using sum() function instead of reduce()
 
# Method B: using sum() function instead of reduce()
 
total_cruise_days2 = sum(cruise.days for cruise in my_cruise)
 
total_cruise_days2 = sum(cruise.days for cruise in my_cruise)
```
+
</source>
  
### Parallel Processing
+
=== Parallel Processing ===
  
 
Please watch below youtube by Dan Bader
 
Please watch below youtube by Dan Bader
371번째 줄: 396번째 줄:
 
- [concurrent.futures](https://www.youtube.com/watch?v=0NNV8FDuck8&list=PLP8GkvaIxJP1z5bu4NX_bFrEInBkAgTMr)
 
- [concurrent.futures](https://www.youtube.com/watch?v=0NNV8FDuck8&list=PLP8GkvaIxJP1z5bu4NX_bFrEInBkAgTMr)
  
```python
+
<source lang=python>
  
 
# Method A
 
# Method A
378번째 줄: 403번째 줄:
 
# Method B
 
# Method B
 
import concurrent.futures
 
import concurrent.futures
```
+
</source>
  
 
## Class & Object
 
## Class & Object
  
### Dynamic property set and get: setattr()/getattr()
+
=== Dynamic property set and get: setattr()/getattr() ===
  
```python
+
<source lang=python>
 
class Cruise():
 
class Cruise():
 
     pass
 
     pass
418번째 줄: 443번째 줄:
 
# NCL Bliss
 
# NCL Bliss
 
# 7
 
# 7
```
+
</source>
  
 
## List
 
## List
  
### Looping List with both index and item: enumerate
+
=== Looping List with both index and item: enumerate ===
  
```python
+
<source lang=python>
 
cruise_hist = ['NCL Bliss', 'NCL Escape', 'Disney Dreamer']
 
cruise_hist = ['NCL Bliss', 'NCL Escape', 'Disney Dreamer']
  
445번째 줄: 470번째 줄:
 
2: NCL Escape
 
2: NCL Escape
 
3: Disney Dreamer
 
3: Disney Dreamer
```
+
</source>
  
### Loop multiple lists using zip()
+
=== Loop multiple lists using zip() ===
  
```python
+
<source lang=python>
 
cruise_lines = ['NCL Bliss', 'RCL Independency', 'Disney Dreamer']
 
cruise_lines = ['NCL Bliss', 'RCL Independency', 'Disney Dreamer']
 
cruise_days = [7, 5,  4]
 
cruise_days = [7, 5,  4]
472번째 줄: 497번째 줄:
 
I cruised with ('Disney Dreamer', 4, 2015)
 
I cruised with ('Disney Dreamer', 4, 2015)
  
```
+
</source>
  
 
## File Operation
 
## File Operation
  
### Using Content Manager
+
=== Using Content Manager ===
  
```python
+
<source lang=python>
 
with open('test.txt', 'rd') as f:
 
with open('test.txt', 'rd') as f:
 
     file_contents = f.read()
 
     file_contents = f.read()
484번째 줄: 509번째 줄:
 
words = file_contents.split(' ')
 
words = file_contents.split(' ')
 
word_count = len(words)
 
word_count = len(words)
```
+
</source>
  
 
## Misc
 
## Misc
  
### Get Help
+
=== Get Help ===
  
 
- In Python Interpreter, type 'help(dir)'
 
- In Python Interpreter, type 'help(dir)'
496번째 줄: 521번째 줄:
 
run help(xyz) or dir(xyz)
 
run help(xyz) or dir(xyz)
  
### Input secret information (e.g. password)
+
=== Input secret information (e.g. password) ===
  
```python
+
<source lang=python>
 
from getpass import getpass
 
from getpass import getpass
  
 
username = input('Username: ')
 
username = input('Username: ')
 
password = getpass('Password: ')
 
password = getpass('Password: ')
```
+
</source>
  
### Unpacking
+
=== Unpacking ===
  
```python
+
<source lang=python>
 
cruise_2018 = ('NCL Bliss', 7)
 
cruise_2018 = ('NCL Bliss', 7)
  
515번째 줄: 540번째 줄:
  
 
print(days_cruised_2018) # 7
 
print(days_cruised_2018) # 7
```
+
</source>
  
```python
+
<source lang=python>
 
cruise_years = [2008, 2015, 2016, 2017, 2018, 2019]
 
cruise_years = [2008, 2015, 2016, 2017, 2018, 2019]
  
530번째 줄: 555번째 줄:
 
my 2nd cruise is in year 2015
 
my 2nd cruise is in year 2015
 
my rest of cruise years are [2016, 2017, 2018, 2019]
 
my rest of cruise years are [2016, 2017, 2018, 2019]
```
+
</source>
  
```python
+
<source lang=python>
 
cruise_years = [2008, 2015, 2016, 2017, 2018, 2019]
 
cruise_years = [2008, 2015, 2016, 2017, 2018, 2019]
  
545번째 줄: 570번째 줄:
 
my latest cruise year is ==>  2019
 
my latest cruise year is ==>  2019
 
my rest of cruise years are [2015, 2016, 2017, 2018]
 
my rest of cruise years are [2015, 2016, 2017, 2018]
```
+
</source>
  
### Ternary Operator
+
=== Ternary Operator ===
  
```python
+
<source lang=python>
  
 
cruise_2018 = 'NCL'
 
cruise_2018 = 'NCL'
563번째 줄: 588번째 줄:
 
my 2019 cruise is my favorite cruise? Y
 
my 2019 cruise is my favorite cruise? Y
 
my 2018 cruise is my favorite cruise? N
 
my 2018 cruise is my favorite cruise? N
```
+
</source>
  
### Large Number format
+
=== Large Number format ===
  
 
- Using underscore (\_) in declaration
 
- Using underscore (\_) in declaration
 
- Using ':," to set group seperator to ',' in f string
 
- Using ':," to set group seperator to ',' in f string
  
```python
+
<source lang=python>
 
china_population = 1_300_000_000_000
 
china_population = 1_300_000_000_000
 
usa_population = 330_000_000_000
 
usa_population = 330_000_000_000
580번째 줄: 605번째 줄:
 
China population = 1,300,000,000,000
 
China population = 1,300,000,000,000
 
USA 330,000,000,000
 
USA 330,000,000,000
```
+
</source>
 
[[category:python]]
 
[[category:python]]

2024년 1월 23일 (화) 23:37 기준 최신판

thumb_up 추천메뉴 바로가기


1 Python Cheat Sheet[편집]

Support/Big Data/Document/My Docs/Python/Python_CheatSheet.MD

1.1 Installation/Config[편집]

1.1.1 PIP[편집]

-- list all installed packages
pip list

-- list only local installed packages in a virtual env
pip list --local

-- search a package
pip list|grep <packagename>

-- show the package location
pip show <packagename>

1.1.2 location of the globally installed packages[편집]

python -m site
>>> import site
>>> print(site.getsitepackages())'

or
>>> import sys
>>> sys.path

1.1.3 location of the locally installed packages[편집]

pythom -m site --user-site


1.1.4 Virtual Env (Python 3.3+)[편집]

  • venv is a package shipped with Python 3, which you can run using python3 -m venv.
  • It serves the same purpose as virtualenv, but only has a subset of its features.
  • virtualenv continues to be more popular than venv, especially since the former supports both Python 2 and 3.

[Difference between virtualenv and venv](https://virtualenv.pypa.io/en/latest/)

1.1.4.1 Install virtualenv[편집]

pip install virtualenv

1.1.4.2 upgrade virtualenv[편집]

pip install --upgrade virtualenv

1.1.4.3 using virtualenv to create a virtual env for a particular python version[편집]

virtualenv -p /usr/local/bin/python3.5 kevin-venv


1.1.5 Create a virtual env[편집]

python -m venv <venv-name>

python -m venv kevin-venv

1.1.5.1 include global python packages[편집]

python -m venv kevin-venv --system-site-packages

1.1.6 using --local to list only local installed packages[편집]

pip list --local

-- typically, you create a folder for your project first;
-- then create a virtual env within/insider of that project folder
>1. mkdir kevin_python_proj1
-- 2a and 2b is same; pick one you like
>2a. python -m venv kevin_python_proj1/.venv
>2b. cd mkdir kevin_python_proj1 && python -m venv .venv

1.1.7 Activate/Deactivate the vtirual env[편집]

1.1.7.1 activate[편집]

source <venv-name>/bin/activate
source kevin-venv/bin/activate

1.1.7.2 deactivate[편집]

deactivate


1.1.8 Delete a virtualenv[편집]

rm -rf <venv-name>
rm -rf kevin-venv


1.1.9 Store copy of python package versions[편집]

-- all packages
pip freeze > requirements.txt

-- only local installed packages
pip freeze --local > requirements.txt


1.1.10 Install all packages from requirements.txt[편집]

pip install -r requriments.txt


1.2 Tips and Tricks[편집]

1.2.1 Date, Time, DateTime, Timezone[편집]

[See this](https://docs.python.org/3/library/datetime.html#datetime.datetime.now)

from datetime import datetime, date, time, timezone, timedelta

current_time = datetime.now(timezone.utc)
print("The current time with UTC is: ", current_time.strftime('%Y-%m-%d %H:%M:%S %Z'))
#The current time with UTC is:  2022-02-15 21:50:52 UT ==> when I run this from laptop, it is 3:50:52 PM,
# this mean Chicago is UTC-6

yesterday = date.today() - timedelta(days=1)
dt = yesterday.strftime("%Y-%m-%d")
print("Yesterday is: ", dt)
# Yesterday is:  2022-02-14

# local time
print("The local time is: ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()));
# The local time is:  2022-02-15 15:50:03


1.2.2 switch value[편집]

a = 10
b = 30

# switch value, now a = 30, b = 10
a,b = b,a


1.2.3 Merging Dictionaries (Python 3.5+)[편집]

x = {'a': 1, 'b': 2}
y = {'c', 3, 'd': 4}

# merged = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
merged = {**x, **y}

# if have same key, then right one win
x = {'a': 1, 'b': 2}
y = {'a', 3, 'c': 4}

# merged = {'a': 3, 'b': 2, 'c': 4}
merged = {**x, **y}

1.2.4 Check if a module contain a class/method[편집]

# Using a list comprehension
import os
[name for name in dir(os) if 'uname' in name.lower()] # return ['uname', 'uname_result']

# After you find the class, you can use built-in help() to see the detail
help(os.uname)

# another example
import collections
[name for name in dir(collections) if 'tuple' in name.lower()] # return ['_tuplegetter', 'namedtuple']

help(collections.namedtuple)
    1. Comprehensions

1.2.5 List Comprehensions[편집]

[expression for item in iterable] [expression for item in iterable if condition]

squares = [x * x for x in range(10)]

even_squares = [x * x for x in range(10) if x % 2 == 0]

# multiple loops
x_dimension = ['a', 'b']
y_dimension = [1, 2, 3]
matrix = [(x,y) for x in x_dimension for y in y_dimension]
#output: [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]

1.2.6 Tuple Comprehensions[편집]

there is no such thing. there is no tuple comprehension

1.2.7 Dictionary Comprehensions[편집]

{key_expression: value_expression for expression in iterable}

word = "dictionary"

# Method A:
letter_count1 = {letter: word.count(letter) for letter in word}

# Method B: better performance using set() to remove duplicated letter from word first
letter_count2 = {letter: word.count(letter) for letter in set(word)}

# with condition
old_salary = {'Kevin': 2000, 'Brandon': 400, 'Elena': 300}
new_salary = {k: v*1.5 if v < 500 else v for (k, v) in old_salary.items()}
#output: new_salary = {'Kevin': 2000, 'Brandon': 600.0, 'Elena': 450.0}

1.2.8 Set Comprehensions[편집]

{expression for item in iterable} {expression for item in iterable if condition}

random_nums = [3, 6, 9, 3, 9, 18, 20, 18]

great_tens = {num for num in random_nums if num > 10}

#output: {18, 20}

1.2.9 Generator Comprehensions[편집]

from pprint import pprint
some_nums = (num for num in range(5))
pprint(some_nums)
#output: <generator object <genexpr> at 0x00000264B87BCF90>
    1. Functional Programming

1.2.10 Named Tuple[편집]

import collections
from pprint import pprint

Cruise = collections.namedtuple(
    "Cruise",
    [
        "year",
        "cruise_line",
        "ship",
        "days",
    ],
)

my_cruise = (
    Cruise(year=2016, cruise_line="RCL", ship="Independency of Seas", days=5),
    Cruise(year=2017, cruise_line="NCL", ship="Escape", days=7),
    Cruise(year=2018, cruise_line="NCL", ship="Bliss", days=7),
)

pprint(my_cruise)

# output
((Cruise(year=2016, cruise_line='RCL', ship='Independency of Seas', days=5),
 Cruise(year=2017, cruise_line='NCL', ship='Escape', days=7),
 Cruise(year=2018, cruise_line='NCL', ship='Bliss', days=7))

1.2.11 Filter()[편집]

# Method A: print only RCL cruise: using filter
rcl_cruise = tuple(
    filter(lambda cruise: cruise.cruise_line.upper() == "RCL", my_cruise)
)

pprint(rcl_cruise)
#output
(Cruise(year=2016, cruise_line='RCL', ship='Independency of Seas', days=5),)

# Method B: print only RCL cruise: using iterator
rcl_cruise2 = tuple(
    cruise for cruise in my_cruise if cruise.cruise_line.upper() == "RCL"
)

pprint(rcl_cruise2)

1.2.12 Map Function[편집]

## Method A: using map function
cruise_history = tuple(
    map(
        lambda cruise: {
            "cruise_line": cruise.cruise_line,
            "name": cruise.ship,
            "past_year": 2022 - cruise.year,
        },
        my_cruise,
    )
)

pprint(cruise_history)

#({'cruise_line': 'RCL', 'name': 'Independency of Seas', 'past_year': 6},
# {'cruise_line': 'NCL', 'name': 'Escape', 'past_year': 5},
# {'cruise_line': 'NCL', 'name': 'Bliss', 'past_year': 4})

# Method B: using generator comprehension and convert it to tuple
cruise_history2 = tuple(
    {
        "cruise_line": cruise.cruise_line,
        "name": cruise.ship,
        "past_year": 2022 - cruise.year,
    }
    for cruise in my_cruise
)

# Another great example: track for each cruise line, which year I took it

# Method A: hard-coded the cruise line dictionary object as initial value for reduce() function

def reducer(acc, val):
    acc[val.cruise_line].append(val.year)
    return acc

cruise_line_year_history = reduce(reducer, my_cruise, {"RCL": [], "NCL": [], "DISNEY": []})

pprint(cruise_line_year_history)
# {'DISNEY': [], 'NCL': [2017, 2018], 'RCL': [2016]}

# Method B: improve on top of Method A using collections.defaultdict
import collections

cruise_line_year_history2 = reduce(reducer, my_cruise, collections.defaultdict(list))

pprint(cruise_line_year_history2)
# defaultdict(<class 'list'>, {'RCL': [2016], 'NCL': [2017, 2018]})
# please notice result doesn't have 'DISNEY' in it

1.2.13 Reduce Function[편집]

# Method A: using reduce() function
from functools import reduce
total_cruise_days = reduce(lambda acc, cruise: acc + cruise.days, my_cruise, 0)

pprint(total_cruise_days)
#output: 19

# Method B: using sum() function instead of reduce()
total_cruise_days2 = sum(cruise.days for cruise in my_cruise)

1.2.14 Parallel Processing[편집]

Please watch below youtube by Dan Bader

- [multiprocessing](https://www.youtube.com/watch?v=aysceqdGFw8&list=PLP8GkvaIxJP1z5bu4NX_bFrEInBkAgTMr)

- [concurrent.futures](https://www.youtube.com/watch?v=0NNV8FDuck8&list=PLP8GkvaIxJP1z5bu4NX_bFrEInBkAgTMr)

# Method A
import multiprocessing

# Method B
import concurrent.futures
    1. Class & Object

1.2.15 Dynamic property set and get: setattr()/getattr()[편집]

class Cruise():
    pass

cruise_2019 = Cruise()

first_key = 'cruise_line'
first_val = 'RCL Symphony'

second_key = 'cruise_days'
second_val = 7

setattr(cruise_2019, first_key, first_val)
setattr(cruise_2019, second_key, second_val)

print(cruise_2019.cruise_line, cruise_2019.cruise_days)
# RCL Symphony 7

cruise_2019_days = getattr(cruise_2019, second_key)
print(cruise_2019_days)
# 7

# convert dictionary to class object
cruise_2018_dict = {'cruise_line': 'NCL Bliss', 'cruise_days': 7}
cruise_2018 = Cruise()

for k, v in cruise_2018_dict.items():
    setattr(cruise_2018, k, v)

for k in cruise_2018_dict.keys():
    print(getattr(cruise_2018, k))

# NCL Bliss
# 7
    1. List

1.2.16 Looping List with both index and item: enumerate[편집]

cruise_hist = ['NCL Bliss', 'NCL Escape', 'Disney Dreamer']

for idx, cruise in enumerate(cruise_hist):
    print(f"{idx}: {cruise}")

# Test
0: NCL Bliss
1: NCL Escape
2: Disney Dreamer

# using start=1
cruise_hist = ['NCL Bliss', 'NCL Escape', 'Disney Dreamer']

for idx, cruise in enumerate(cruise_hist, start=1):
    print(f"{idx}: {cruise}")

# Test
1: NCL Bliss
2: NCL Escape
3: Disney Dreamer

1.2.17 Loop multiple lists using zip()[편집]

cruise_lines = ['NCL Bliss', 'RCL Independency', 'Disney Dreamer']
cruise_days = [7, 5,  4]
cruise_years = [2018, 2016, 2015]

for cruise_line, cruise_day, cruise_year in zip(cruise_lines, cruise_days, cruise_years):
    print(
        f"I cruised with {cruise_line} in year {cruise_year} for {cruise_day} days")

# Test
I cruised with NCL Bliss in year 2018 for 7 days
I cruised with RCL Independency in year 2016 for 5 days
I cruised with Disney Dreamer in year 2015 for 4 days

# cruise_tuple is a tuple in below
for cruise_tuple in zip(cruise_lines, cruise_days, cruise_years):
    print(f"I cruised with {cruise_tuple} ")

# Test
I cruised with ('NCL Bliss', 7, 2018)
I cruised with ('RCL Independency', 5, 2016)
I cruised with ('Disney Dreamer', 4, 2015)
    1. File Operation

1.2.18 Using Content Manager[편집]

with open('test.txt', 'rd') as f:
    file_contents = f.read()

words = file_contents.split(' ')
word_count = len(words)
    1. Misc

1.2.19 Get Help[편집]

- In Python Interpreter, type 'help(dir)' - In Python Interpreter, type build-in 'dir(xyz)'

Make sure you import the module(xyz) you want to investigate before you run help(xyz) or dir(xyz)

1.2.20 Input secret information (e.g. password)[편집]

from getpass import getpass

username = input('Username: ')
password = getpass('Password: ')

1.2.21 Unpacking[편집]

cruise_2018 = ('NCL Bliss', 7)

# using _ as a variable is a convention in Python
# to indicate you are not use that variable
_, days_cruised_2018 = cruise_2018

print(days_cruised_2018) # 7
cruise_years = [2008, 2015, 2016, 2017, 2018, 2019]

first_cruise_yr, second_cruise_yr, *rest_cruise_yrs = cruise_years

print(f"my very 1st cruise is in year {first_cruise_yr}")
print(f"my 2nd cruise is in year {second_cruise_yr}")
print(f"my rest of cruise years are {rest_cruise_yrs}")

# Test
my very 1st cruise is in year 2008
my 2nd cruise is in year 2015
my rest of cruise years are [2016, 2017, 2018, 2019]
cruise_years = [2008, 2015, 2016, 2017, 2018, 2019]

first_cruise_yr, *rest_cruise_yrs, latest_cruise_yr = cruise_years

print(f"my very 1st cruise is in year {first_cruise_yr}")
print(f"my latest cruise year is ==>  {latest_cruise_yr}")
print(f"my rest of cruise years are {rest_cruise_yrs}")

# Test
my very 1st cruise is in year 2008
my latest cruise year is ==>  2019
my rest of cruise years are [2015, 2016, 2017, 2018]

1.2.22 Ternary Operator[편집]

cruise_2018 = 'NCL'
cruise_2019 = 'RCL'

favorite_flag = 'Y' if cruise_2019 == my_favorite_cruise else 'N'
print(f"my 2019 cruise is my favorite cruise? {favorite_flag}")

favorite_flag = 'Y' if cruise_2018 == my_favorite_cruise else 'N'
print(f"my 2018 cruise is my favorite cruise? {favorite_flag}")

# Test
my 2019 cruise is my favorite cruise? Y
my 2018 cruise is my favorite cruise? N

1.2.23 Large Number format[편집]

- Using underscore (\_) in declaration - Using ':," to set group seperator to ',' in f string

china_population = 1_300_000_000_000
usa_population = 330_000_000_000

print(f"China population = {china_population:,}")
print(f"USA {usa_population:,}")

# Test
China population = 1,300,000,000,000
USA 330,000,000,000