2022. 12. 15. 11:43ㆍBackup
매번 다른 언어로 코딩하다보면, 이런 간단한 문법도 잊을 때가 있어서 백업해본다.
수정 및 추가 중. iter과 next 또한 추가

참.
여기에 또 알아두면 좋은 것은,
Starting from a specific point in a for-loop 하고 싶으면
n = 100
for k in range(3,100):
print k # It starts at 3
for k in range(0,10,2):
print k
#output is 0,2,4,6,8
# 혹은
for x in languages[2::]: # 이미 선언한 languages배열 을 slicing한다.
print x
arr = [2, 7, 10]
for idx in range(len(arr)):
print(idx, arr[idx])
arr = [2, 7, 10]
for idx, val in enumerate(arr):
print(idx, val)
# Output:
# 0 2
# 1 7
# 2 10
arr = [2, 7, 10] # 두번째 인자로 정수를 전달하면 시작하는 index 값을 조정할 수도 있다.
for idx, val in enumerate(arr, 5):
print(idx, val)
시작시점과 증분이 얼마나 될지를 정할 수 있다.






위의 경우의 형식은 이렇게 된다.
[조건 만족시 출력값 if 조건 else 조건 불만족시 출력값 for i in 배열]
# 예제. 배열 Element당 제곱을 구하자
# 방법 1
v_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
results = []
for i in v_list:
results.append(i**2)
print(results) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 방법 2
v_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
results = list(map(lambda x: x**2, v_list))
print(results) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 방법 3
v_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
results = [x**2 for x in v_list]
print(results) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
이 예제는 값 자체를 곱했다.
if else 케이스가 아니라 모든 element에 동일한 식이 적용되기 때문에 위와 약간 다르다.
난 보통 방법2로 진행했는데, 경우에 따라 방법3 이 더 편한 것 같기도 하다.
dictionary 타입에서도 list comprehension을 사용할 수 있다.

my_dict.keys() 타입은 iterable 한 객체이며 이것을 list(my_dict.keys()) 이런 식으로 list로 이용할 수도 있다.
2.7까지는 my_dict.keys()가 원래 list타입이었다.
그러나 3.0이후에는 리스트를 리턴하기 위해 메모리 낭비되는 것을 지양하기 위해, dict_keys 타입을 리턴한다. 기본적인 반복구문에서는 dict_keys 자체로 사용해도 iterable하다.. 그러나, type 상으로는 list가 아니라 dict_keys 임을 알고 있어야 하겠다.
https://cjh5414.github.io/python-for-index/
https://dojang.io/mod/page/view.php?id=2408
https://godoftyping.wordpress.com/2016/05/22/%ED%96%A5%EC%83%81%EB%90%9C-for%EB%AC%B8/
https://stackoverflow.com/questions/41555122/starting-from-a-specific-point-in-a-for-loop
'Backup' 카테고리의 다른 글
AWS Certified Solutions Architect - Associate 카드 결제 실패 (0) | 2023.01.02 |
---|---|
git instaweb -llighttpd not found. Install lighttpd or use --httpd to specify another httpd daemon. (1) | 2022.12.29 |
Python3 function definition | 형 힌트 지원 | typing (0) | 2022.12.14 |
vscode extension backup (0) | 2022.12.13 |
webpack 최소설정 (0) | 2022.12.09 |