IT 세계의 후아
[python]zip 활용 - dict, 리스트, 문자열, 반복문 본문
※ for N in zip(iterable1, iterable2, ...)
내장함수로, iterable 객체 여러개를 받아 tuple로 묶어주는 역할
for z in zip("abc", [1,2,3]):
print(z)
("a", 1)
("b", 2)
("c", 3)
※ for k,v in dict(zip(리스트1, 리스트2)
key: 리스트1, value: 리스트2
# 프로그래머스 수 조작하기1
# control: 문자열 'wdsaaw...'
def solution(n, control):
w = control.count('w')
s = control.count('s')
d = control.count('d')
a = control.count('a')
return n + w - s + 10*(d-a)
# 다른 사람 풀이
key = dict(zip(['w','s','d','a'], [1,-1,10,-10]))
return n + sum([key[c] for c in control])
# 프로그래머스 수 조작하기2
def solution(numLog):
res = ""
num_dic = dict(zip([-1, 1, -10, 10], ['w','s','d','a'])) # key-value 순서 뒤집기 아이디어!
for i in range(len(numLog)-1):
res += num_dic[numLog[i] - numLog[i+1]]
return res
https://yunwoong.tistory.com/159
※ for x, y, ... in zip(리스트1, 문자열, 리스트2, ...)
# 프로그래머스 부분 문자열 이어붙여 문자열 만들기
def solution(str, parts):
return ''.join([str[i][parts[i][0]:parts[i][1]+1] for i in range(len(str))])
# 다른 사람 풀이-zip 활용
return ''.join([x[y[0]:y[1]+1] for x,y in zip(my_strings, parts)])
'Coding > Python' 카테고리의 다른 글
[python]반복문 (0) | 2024.04.19 |
---|---|
[python]리스트 순열, 조합 (1) | 2024.04.18 |
[python]리스트 값 추가, 삭제/요소 곱 - reduce, prod) (0) | 2024.04.17 |
[python]문자열 인덱싱 (0) | 2024.04.17 |
[python]조건문 (0) | 2024.04.17 |