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
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@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