아래 링크 참조
http://gentooboy.tistory.com/212
이를 응용하여 기존 list의 값을 교체할 경우 아래와 같이 가능하다.
list = ['a', 'b', 'c', 'd']
tfdata = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
for x in range(len(list)):
list[x] = tfdata[list[x]]
print(list) # 결과 => [1, 2, 3, 4]
(tuple의 경우 수정이 안되므로 list로 바꾼 후 수정하고 tuple로 다시 바꾸면 된다.)
또한, 본 알고리즘을 활용하면
일급함수를 지원하는 파이썬의 특성을 생각할 때
dict의 value에 함수를 넣을 수도 있다는 점을 응용해보면 좋을 듯.
아래 예제를 참고하자.
def add(a, b):
return '덧셈: ' + str(a + b)
def sub(a, b):
return '뺄셈: ' + str(a - b)
def mul(a, b):
return '곱셈: ' + str(a * b)
def div(a, b):
try:
return '나눗셈: ' + str(a / b)
except ZeroDivisixxxxonError as zeroerr:
return 'Error: ' + str(zeroerr)
cal_list = ['a', 'b', 'c', 'd']
tfdata = {'a' : add, 'b' : sub, 'c' : mul, 'd' : div}
for x in range(len(cal_list)):
cal_list[x] = tfdata[cal_list[x]]
print(cal_list) # 결과 => [<function add at 0x00000000028E77B8>, <function sub at 0x00000000028E79D8>, <function mul at 0x00000000028E7D08>, <function div at 0x00000000028E7D90>]
print([x(1,2) for x in cal_list]) # ['덧셈: 3', '뺄셈: -1', '곱셈: 2', '나눗셈: 0.5']