Skip to content

Instantly share code, notes, and snippets.

@choco9966
Last active July 17, 2018 06:45
Show Gist options
  • Save choco9966/c31e0407b6cb18fc008377b796e751cb to your computer and use it in GitHub Desktop.
Save choco9966/c31e0407b6cb18fc008377b796e751cb to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 강사님 코멘트\n",
"\n",
"파이썬에서 스타일 가이드를 읽고 앞으로 코드를 작성할때 참고해주세요.\n",
"\n",
"대문자만으로 변수를 생성하지 않습니다.\n",
"\n",
"https://www.python.org/dev/peps/pep-0008/"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'나이': '25', '생일': '1월1일', '연락처': '010-1234-5678'},\n",
" {'나이': '65', '생일': '1월18일', '연락처': '010-1243-1234'},\n",
" {'나이': '59', '생일': '3월2일', '연락처': '010-1234-4321'},\n",
" {'나이': '26', '생일': '3월11일', '연락처': '010-1234-4313'}]"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"me = {'나이':'25' , '생일':\"1월1일\", '연락처':'010-1234-5678'}\n",
"father = {\"나이\" : '65',\"생일\" : \"1월18일\",\t\"연락처\" : \"010-1243-1234\" }\n",
"mother = {\"나이\" : '59',\"생일\" : \"3월2일\", \"연락처\" : \"010-1234-4321\"}\n",
"brother = {\"나이\" : '26',\"생일\" : \"3월11일\",\"연락처\" : \"010-1234-4313\"}\n",
"\n",
"family = []\n",
"family.append(me)\n",
"family.append(father)\n",
"family.append(mother)\n",
"family.append(brother)\n",
"family"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 강사님 코멘트\n",
"\n",
"결과적으로 나와야하는 CSV값은 다음과 같습니다.\n",
"\n",
"나이, 생일, 연락처 \n",
"25, 1월 1일, 010-1234-5678 \n",
"65, 1월 18일, 010-1234-1234 \n",
"59, 3월 2일, 010-1234-4321 \n",
"26, 3월 11일, 010-1234-4313 "
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"나이, 생일, 연락처\n"
]
}
],
"source": [
"for i in list(family[0].keys()):\n",
" if i == list(family[0].keys())[-1]:\n",
" print(i)\n",
" else:\n",
" print(i, end= \", \") "
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"25, 1월1일, 010-1234-5678\n",
"65, 1월18일, 010-1243-1234\n",
"59, 3월2일, 010-1234-4321\n",
"26, 3월11일, 010-1234-4313\n"
]
}
],
"source": [
"for i in range(0,len(list(family[0].keys()))+1):\n",
" for j in family[i].values():\n",
" if j == list(family[i].values())[-1]:\n",
" print(j)\n",
" else:\n",
" print(j, end=\", \")"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"나이, 생일, 연락처\n",
"25, 1월1일, 010-1234-5678\n",
"65, 1월18일, 010-1243-1234\n",
"59, 3월2일, 010-1234-4321\n",
"26, 3월11일, 010-1234-4313\n"
]
}
],
"source": [
"for i in list(family[0].keys()):\n",
" if i == list(family[0].keys())[-1]:\n",
" print(i)\n",
" else:\n",
" print(i, end= \", \")\n",
"for i in range(0,len(list(family[0].keys()))+1):\n",
" for j in family[i].values():\n",
" if j == list(family[i].values())[-1]:\n",
" print(j)\n",
" else:\n",
" print(j, end=\", \")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 강사님 코멘트"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"# 기존코드\n",
"# 구글에서 PEP 20 을 검색하여(영문), 각 알파벳이 몇번 쓰이는지 딕셔너리에 담아보세요 출력 예 ) {‘a’: 34, ‘b’: 26, … , ‘z’: 3}"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"PEP20= \"\"\"\n",
"PEP: 20\n",
"Title: The Zen of Python\n",
"Version: $Revision$\n",
"Last-Modified: $Date$\n",
"Author: tim.peters@gmail.com (Tim Peters)\n",
"Status: Active\n",
"Type: Informational\n",
"Content-Type: text/x-rst\n",
"Created: 19-Aug-2004\n",
"Post-History: 22-Aug-2004\n",
"\n",
"\n",
"\n",
"Abstract\n",
"========\n",
"\n",
"Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding\n",
"principles for Python's design into 20 aphorisms, only 19 of which\n",
"have been written down.\n",
"\n",
"\n",
"The Zen of Python\n",
"=================\n",
"\n",
"::\n",
"\n",
" Beautiful is better than ugly.\n",
" Explicit is better than implicit.\n",
" Simple is better than complex.\n",
" Complex is better than complicated.\n",
" Flat is better than nested.\n",
" Sparse is better than dense.\n",
" Readability counts.\n",
" Special cases aren't special enough to break the rules.\n",
" Although practicality beats purity.\n",
" Errors should never pass silently.\n",
" Unless explicitly silenced.\n",
" In the face of ambiguity, refuse the temptation to guess.\n",
" There should be one-- and preferably only one --obvious way to do it.\n",
" Although that way may not be obvious at first unless you're Dutch.\n",
" Now is better than never.\n",
" Although never is often better than *right* now.\n",
" If the implementation is hard to explain, it's a bad idea.\n",
" If the implementation is easy to explain, it may be a good idea.\n",
" Namespaces are one honking great idea -- let's do more of those!\n",
"\n",
"\n",
"Easter Egg\n",
"==========\n",
"\n",
"::\n",
"\n",
" >>> import this\n",
"\n",
"\n",
"Copyright\n",
"=========\n",
"\n",
"This document has been placed in the public domain.\n",
"\n",
"\n",
"..\n",
" Local Variables:\n",
" mode: indented-text\n",
" indent-tabs-mode: nil\n",
" sentence-end-double-space: t\n",
" fill-column: 70\n",
" End:\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a': 78, 'b': 28, 'c': 36, 'd': 36, 'e': 144, 'f': 19, 'g': 21, 'h': 48, 'i': 89, 'j': 0, 'k': 2, 'l': 53, 'm': 30, 'n': 78, 'o': 73, 'p': 40, 'q': 0, 'r': 52, 's': 73, 't': 128, 'u': 31, 'v': 10, 'w': 7, 'x': 9, 'y': 25, 'z': 2}\n"
]
}
],
"source": [
"lower_PEP20 = PEP20.lower()\n",
"lower_PEP20\n",
"\n",
"# 다른방법이 궁금합니다.\n",
"alphabet_list=list('abcdefghijklmnopqrstuvwxyz')\n",
"\n",
"char_dict = {}\n",
"\n",
"for el in alphabet_list :\n",
" char_dict[el] = lower_PEP20.count(el)\n",
"\n",
"print(char_dict)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 문자 갯수 카운트\n",
"alphabet_list=list('abcdefghijklmnopqrstuvwxyz')\n",
"\n",
"꼭 리스트로 바꿔야될까요? \n",
"바꾸지 않아도 str타입도 반복가능합니다. \n",
"\n",
"보장된 코드 사용하기 \n",
"지금 알파벳 a부터 ~ z까지 포함된 리스트를 반복하고 있습니다. \n",
"이러한 코드를 볼때 남이 본다면, 혹은 현우님도 코드를 작성하시고 \n",
"\"빠진 문자가 있는지~?\" 확인하는 작업이 필요하게 될지도 모릅니다. \n",
"\n",
"좀 더 보장되게 코드를 작성한다면 남이보더라도, 혹은 현우님이 나중에 코드를 보더라도 \n",
"또는 에러가 발생하더라도 이부분에 대해서는 안심하고 넘어갈수있을거 같습니다. \n",
"\n",
"아마 현우님도 이러한 하드코딩된(코드 안엣 직접 타이핑된) 방법이 맘에들지 않아 \n",
"다른방법이 있는지 질문주신거 같습니다.\n",
"\n",
"음.. 생각을해보니 3가지 방법 정도가 있을거 같습니다. \n",
"\n",
"3가지 방법 다 구현해보시기 바랍니다. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1번째\n",
"알파벳 a~z의 의 갯수가 26개인걸 알고 있습니다. \n",
"리스트의 포함된 글자가 중복되지 않았고 동시에 리스트의 길이가 26 이면 \n",
"보장됬다고 볼 수 있습니다.\n",
"\n",
"> 대충 눈으로 봤을때 대문자나, 불필요한 다른 문자열이 포함되었는지는 확인가능하니까요."
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a': 78, 'b': 28, 'c': 36, 'd': 36, 'e': 144, 'f': 19, 'g': 21, 'h': 48, 'i': 89, 'j': 0, 'k': 2, 'l': 53, 'm': 30, 'n': 78, 'o': 73, 'p': 40, 'q': 0, 'r': 52, 's': 73, 't': 128, 'u': 31, 'v': 10, 'w': 7, 'x': 9, 'y': 25, 'z': 2}\n"
]
}
],
"source": [
"lower_PEP20 = PEP20.lower()\n",
"lower_PEP20\n",
"\n",
"# 다른방법이 궁금합니다.\n",
"alphabet_list=list('abcdefghijklmnopqrstuvwxyz')\n",
"if len(set(alphabet_list)) != 26:\n",
" print(\"list가 잘못되었습니다.\")\n",
"\n",
"char_dict = {}\n",
"\n",
"for el in alphabet_list :\n",
" char_dict[el] = lower_PEP20.count(el)\n",
"\n",
"print(char_dict)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2번째\n",
"\n",
"ascii코드표를 이용하는 방법입니다.\n",
"\n",
"구글에 아스키코드표를 검색하시면 'a'를 뜻하는 특정숫자와 'z'를 뜻하는 특정숫가까지를\n",
"확인할 수 있을겁니다.\n",
"이 숫자들은 연속적입니다.\n",
"\n",
"다음 함수를 이용해서 구현해보세요.\n",
"\n",
"```\n",
">>> chr(97) \n",
"'a'\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a': 78, 'b': 28, 'c': 36, 'd': 36, 'e': 144, 'f': 19, 'g': 21, 'h': 48, 'i': 89, 'j': 0, 'k': 2, 'l': 53, 'm': 30, 'n': 78, 'o': 73, 'p': 40, 'q': 0, 'r': 52, 's': 73, 't': 128, 'u': 31, 'v': 10, 'w': 7, 'x': 9, 'y': 25, 'z': 2}\n"
]
}
],
"source": [
"alphabet_list = list()\n",
"for i in range(97,97+26):\n",
" alphabet_list.append(chr(i))\n",
"\n",
"char_dict = {}\n",
"\n",
"for el in alphabet_list :\n",
" char_dict[el] = lower_PEP20.count(el)\n",
"\n",
"print(char_dict)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3번째\n",
"\n",
"가장 간단한 방법입니다.\n",
"\n",
"파이썬에서 이미 구현해서 모듈안에 숨겨두었습니다.\n",
"\n",
"어떤 기능을 사용할수있을지 찾아보세요"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Formatter',\n",
" 'Template',\n",
" '_ChainMap',\n",
" '_TemplateMetaclass',\n",
" '__all__',\n",
" '__builtins__',\n",
" '__cached__',\n",
" '__doc__',\n",
" '__file__',\n",
" '__loader__',\n",
" '__name__',\n",
" '__package__',\n",
" '__spec__',\n",
" '_re',\n",
" '_string',\n",
" 'ascii_letters',\n",
" 'ascii_lowercase',\n",
" 'ascii_uppercase',\n",
" 'capwords',\n",
" 'digits',\n",
" 'hexdigits',\n",
" 'octdigits',\n",
" 'printable',\n",
" 'punctuation',\n",
" 'whitespace']"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from string import ascii_lowercase\n",
"dir(string)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a': 78, 'b': 28, 'c': 36, 'd': 36, 'e': 144, 'f': 19, 'g': 21, 'h': 48, 'i': 89, 'j': 0, 'k': 2, 'l': 53, 'm': 30, 'n': 78, 'o': 73, 'p': 40, 'q': 0, 'r': 52, 's': 73, 't': 128, 'u': 31, 'v': 10, 'w': 7, 'x': 9, 'y': 25, 'z': 2}\n"
]
}
],
"source": [
"lower_PEP20 = PEP20.lower()\n",
"lower_PEP20\n",
"\n",
"# 다른방법이 궁금합니다.\n",
"alphabet_list= ascii_lowercase\n",
"if len(set(alphabet_list)) != 26:\n",
" print(\"list가 잘못되었습니다.\")\n",
"\n",
"char_dict = {}\n",
"\n",
"for el in alphabet_list :\n",
" char_dict[el] = lower_PEP20.count(el)\n",
"\n",
"print(char_dict)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"# 다음 형태를 List Comprehension을 이용해 생성해보세요.\n",
"# 1. [1, 2, 3, 4, 5, 6]\n",
"# 2. [6, 5, 4, 3, 2, 1]\n",
"# 3. [[1, 2, 3], [1, 2, 3], [1, 2, 3]]\n",
"# 4. [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
"\n",
"print([x for x in range(1, 6+1)])\n",
"\n",
"#이거 될거같은데 왜 안될까요?\n",
"print([x for x in range(1, 6+1)].reverse())\n",
"\n",
"print([[i for i in range(1, 3+1)] for _ in range(3)])\n",
"\n",
"print([[x + i for x in range(1, 3+1)] for i in range(0,6+1,3)])"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 6]\n"
]
}
],
"source": [
"print([x for x in range(1, 6+1)])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 이거 왜 None값 나오는지 잘 모르겠습니다."
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"print([x for x in range(1, 6+1)].reverse())"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1, 2, 3], [1, 2, 3], [1, 2, 3]]\n"
]
}
],
"source": [
"print([[i for i in range(1, 3+1)] for _ in range(3)])\n"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n"
]
}
],
"source": [
"print([[x + i for x in range(1, 3+1)] for i in range(0,6+1,3)])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@COCOLMAN
Copy link

Iterable

for문에서 반복가능한 객체는 Iterable객체 입니다.

리스트여야만 되는게 아닙니다

리스트도 Iterable객체 이기 때문에 가능합니다.

파이썬에서 Iterable객체는

list, tuple, set, dict, str
이 있습니다.

불필요하게 list로 형변환하는 경우가 너무 많습니다.

@COCOLMAN
Copy link

csv만들기

고생하셨습니다.

음 약간에 문제점들이 보입니다.

일단 간단한 코멘트는 달아두었습니다.

그리고 print하는게 아니라 어떤 value(str)를 만들어서 출력하는 형태로 바꿔주세요!

csv형태의 string을 만들어서 최종 종료시 출력


me = {'나이':'25' , '생일':"1월1일", '연락처':'010-1234-5678'}
father = {"나이" : '65',"생일" : "1월18일",   "연락처" : "010-1243-1234" }
mother = {"나이" : '59',"생일" : "3월2일", "연락처" : "010-1234-4321"}
brother = {"나이" : '26',"생일" : "3월11일","연락처" : "010-1234-4313"}
​
​
family = []
family.append(me)
family.append(father)
family.append(mother)
family.append(brother)
family.append(brother)
family.append(brother)
family
​
for i in list(family[0].keys()):
    if i == list(family[0].keys())[-1]: # 마지막에 컴마가 안찍히기 위한 방법이네요.
        print(i)
    else:
        print(i, end= ", ")
​
# replace, lstrip, join을 이용해서 마지막 comma 제거하기
​
        
for i in range(0, len(family[0].keys())+1): # 우연에 일치로 작동되고 있습니다. 가족 인원을 몇명 더 추가해보세요.
    for j in family[i].values():
        if j == list(family[i].values())[-1]:
            print(j)
        else:
            print(j, end=", ")

@COCOLMAN
Copy link

알파벳 검증하기

1번째
lower_PEP20 = PEP20.lower()
lower_PEP20

# 다른방법이 궁금합니다.
alphabet_list=list('abcdefghijklmnopqrstuvwxyz') # 리스트로 바꿀필요 없습니다.
if len(set(alphabet_list)) != 26:
    print("list가 잘못되었습니다.")

char_dict = {}

for el in alphabet_list :
    char_dict[el] = lower_PEP20.count(el)

print(char_dict)
3번째
from string import ascii_lowercase

lower_PEP20 = PEP20.lower()
lower_PEP20

# 다른방법이 궁금합니다.
# alphabet_list= ascii_lowercase 
# if len(set(alphabet_list)) != 26: # 1번방법으로 검증할 필요가 없습니다. 모듈은 믿어도됩니다.
#     print("list가 잘못되었습니다.")

char_dict = {}

for el in ascii_lowercase: # 바로 사용하시면 됩니다.
    char_dict[el] = lower_PEP20.count(el)

print(char_dict)

@COCOLMAN
Copy link

None이 나오는 이유

list는 변경가능한객체, 즉 mutable이기 때문입니다.

만약 문자열처럼 변경불가능(immutable)한 객체라면 출력가능할겁니다.

immutable객체 수정

a = 'abc'
b = a.title() # 첫 문자를 대문자로 변경하는 메소드
print(a) # 변경 불가능하기 때문에 여전히 'abc'
print(b) # 변경 불가능하기때문에 바뀐값을 리턴했습니다. 그래서 변경된 값이 b에 들거아 있습니다. 'Abc'출력

mutable객체 수정

a = [1, 2, 3]
b = a.reverse()
print(b) # None 출력 reverse 함수가 변경가능한 객체를 수정했기때문에, 수정된 값을 리턴시키지 않습니다.
print(a) # [3, 2, 1] 출력, 리스트가 수정되어 있습니다.

그렇기 때문에 다음 코드는 다음과 같이 수정가능합니다.

print([x for x in range(1, 6+1)].reverse())

에서

a = [x for x in range(1, 6+1)]
a.reverse()
print(a)

으로

혹은

print(list(reversed([x for x in range(1, 6+1)])))

으로

reverse함수를 쓰지 말고 해보세요!

range 함수의 step을 활용해서 해결해보세요

>>> help(range)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment