Post date: Apr 8, 2016 11:12:55 AM
1차원 배열이 있을때 각 배열의 요소를 가지고 어떤 연산을 할때가 많은데요.
예를들면
import numpy as np
theta_all = np.array([0, np.pi/4, np_pi/2, 3*np_pi/4, np.pi])
theta_all 이라는 1차원 배열이 다양한 각도값을 가지고 있고, 이것을 가지고 다음과 같은 계산을 하려고 한다고 해보죠.
np.array([0, 2, 4, 8, 10])*np.sin(theta_all)
물론, numpy는 배열에 직접 적용할 수 있으니까 for-loop를 쓰지않고 위에서 처럼 한줄에 계산할 수 도 있지만, 그렇게 할 수 없는 경우라 가정하고, for-loop로 이 계산을 한다면
k_const = np.array([0, 2, 4, 8, 10])
for idx in range(5):
foo = k_const[idx]*np.sin(theta_all[idx])
print(k_const[idx],np.sin(theta_all[idx]), foo)
이렇게 할 수 있겠죠. 아니면 range(5)에서 "5"와 같이 느닷없이 숫자가 등장하는 것은 좋은 프로그램 방법이 아니니까, 아래와 같이 고칠수도 있습니다
for idx in range(len(k_const)):
foo = k_const[idx]*np.sin(theta_all[idx])
print(k_const[idx],np.sin(theta_all[idx]), foo)
여기서 len(...) 함수는 배열의 크기를 계산해 줍니다. 여기까지는 그냥 다른 프로그램 언어를 썼을때도 비슷하게 짜는 방식인데요.
좀 더 python스러운 프로그램을 한다면 다음과 같이 enumerate 함수를 사용하는 것이 좋습니다.
for idx, theta in enumerate(theta_all):
foo = k_const[idx]*np.sin(theta)
print(k_const[idx],np.sin(theta), foo)
첫줄, for idx, theta in enumerate(theta_all)에서:
1) idx는 자동으로 배열의 index를 0부터 세면서 증가하게되고, 즉 idx는 0, 1, 2, 3, 4 순서로 증가합니다.
2) theta는 자동으로 theta_all의 값을 첫번째부터 마지막까지 순서대로 대입이 됩니다.
물론, 똑같은 효과를 k_const로 할 수도 있습니다.
for idx, k in enumerate(k_const):
foo = k*np.sin(theta_all[idx])
print(k,np.sin(theta_all[idx]), foo)
k_const하고 theta_all을 동시에 enumerate에 넣을 수는 없을까요. 할 수 있습니다. 대신 enumerate가 아니고 zip을 써야 합니다.
for k, theta in zip(k_const, theta_all):
foo = k*np.sin(theta)
print(k,np.sin(theta), foo)