[Python] for statement

2023. 7. 30. 22:31·Programming
728x90
728x90

for statement는 loop를 위한 control structure의 대표격이다.

더보기

https://ds31x.blogspot.com/2023/07/basic-control-structures-and-control.html

 

Basic : Control Structures and Control Flow

Control Structure 프로그램을 구성하는 statement (=executable code)들이 실행되는 순서를 제어하는 방법을 abstraction한 것이 control structure이며 이를 통해 실행순서를 제어하는 것을 flow c...

ds31x.blogspot.com


Python에서는 iterable 객체 (주로 collection type의 객체들)이
가지고 있는 item들을 iterate(순회)하는 용도로 사용된다.

 

프로그래밍을 배울 때, 구구단 출력과 같은 고전적인 예를 통해 배우고, 정말 기본 중의 기본으로 활용된다. 단, NumPy등을 익히게 되면서 loop가 아닌 matrix 를 이용한 처리 (쉽게 생각하면 많은 memory를 이용하여 반복을 덜하는 방식이라고 할 수 있음)가 보다 효율적이기 때문에 정말 필요한 경우 아니면 쓰지 말라고 애기를 하게 되지만...

더보기

2023.06.07 - [Programming] - [Python] Iterable and Iterator, plus Generator

 

[Python] Iterable and Iterator, plus Generator

Iterable and Iteartor, and GeneratorIterable for 문에서 in 뒤에 위치하여 iterate (반복, 순회)가 가능한 object를 가르킴.__iter__() 라는 special method를 구현하고 있으며, 이를 통해 자신에 대한 iterator object를 반

dsaint31.tistory.com


 

for statement는 정말 기본 중의 기본이다.

(반복을 얼마나 효율적으로 하느냐가 성능 뿐 아니라 유지보수의 난이도를 결정하기 때문에...)


기본 사용법

https://datagy.io/python-for-loop/

 

for loop_variable in iterable_obj:
    for_block # loop body 또는 loop block으로 불림.

for statement의 사용법은 다음과 같음.

  • keyword for 로 시작함.
  • 이후 loop variables가 놓인다. loop variables는 매 iteration에서 뒤에 놓인 iterable 객체의 item들이 할당됨.
  • 이후 keyword in 이 놓임. (in 이전이 loop vairables이고 이후가 iterable객체들이 놓임.)
  • 이후 iterate가 이루어질 iterable 객체가 놓임 (복수 개를 사용시 zip으로 묶어주면 됨.).
  • 이후 : 가 놓임 (for statement는 compound statement로 : 이후 다음 라인들은 for statement의 반복될 code block임.

code block은 for statement가 시작하는 첫번째 line 보다 한단계 더 indentation 이루어짐.
이후 indent level이 감소하면 해당 code block이 종료함.


list와 함께 사용하기

l = [0,1,2,3,4,5]
for c in l:
  print(c)
  print('\n')
  • list l의 item들이 순서대로 loop variable c에 할당되고,
  • loop block이 수행되고
  • 이후 다시 loop variable c에 다음 item이 할당되고
  • 또 loop block이 수행되고
  • 위 과정이 l의 마지막 item까지 반복됨.

결과는 다음과 같음.

0

1

2

3

4

5

string과 함께 사용하기.

string도 sequence type이기 때문에 다음과 같이 동작가능함.

s = 'abce1234ABC'
for c in s:
  if c.isdigit():
    print(c)
  • 숫자에 해당하는 character c만이 출력이 됨.

결과는 다음과 같음.

1
2
3
4

range 객체와 함께 사용하기 *

C에서처럼 시작과 끝 index에 해당하는 숫자를 이용하는 경우는 range 객체를 사용하는게 효율적이다.

더보기

2023.06.07 - [Programming] - [Python] range and enumerate

 

[Python] range and enumerate

range 란엄밀하게 애기하면, range 는 숫자들의 immutable sequence (=iterable)를 나타내는 built-in type이다.  즉, 흔히 built-in function으로 애기하는 range() 는 사실은 range class의 instance를 생성하는 생성자에

dsaint31.tistory.com



list나 tuple등은 자신의 모든 item들을 memory에 할당하는 객체이기 때문 매우 큰 수의 범위를 가지는 for statement에서 사용하기는 비효율적임.

for c in range(0,21,2):
    print(c)
  • ( [0,20] ) 에서 stepsize를 2로 취하기 때문에 짝수만이 출력됨.

결과는 다음과 같음.

0
2
4
6
8
10
12
14
16
18
20

 


복수 iterable에서 반복하기

zip 함수로 여러 iterable 객체를 묶어주어 각 iteration에 복수의 loop varaible을 사용할 수 있음.
단, zip으로 묶이는 각 iterable의 item 갯수가 다른 경우 짧은 쪽에 의해 반복횟수가 결정됨.

다음의 예를 확인하라.

a = [0,1,2,3,4]
s = 'abcdefgh'

for i,c in zip(a,s):
  print(f'{i},{c}')
  • 5번의 반복만 이루어지는 것을 확인할 것.
  • loop variable을 하나로 두면, 해당 variable은 tuple 객체가 된다.

결과는 다음과 같음.

0,a
1,b
2,c
3,d
4,e

code block인 loop block에는 다양한 statement가 놓일 수 있으며, 이는 중첩된 loop를 만들 수 있음.
(nested if statement에서와 비슷)


참고: break check - else

https://ds31x.tistory.com/100

 

[Python] else : break checker

일반적으로 else의 경우, 앞서의 if 와 elif문들에서 실행된 block이 없는 경우 수행되는 것을 의미한다. 그런데 python에서는 for와 while과 같은 loop structure 에서도 else를 뒤에 붙여서 break로 해당 loop가

ds31x.tistory.com


Reference

https://gist.github.com/dsaint31x/f28b8b3c59483abdb3119aa31ec44d01

 

py_for_Ex.ipynb

py_for_Ex.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

2023.06.07 - [Programming] - [Python] Iterable and Iterator, plus Generator

 

[Python] Iterable and Iterator, plus Generator

Iterable for 문에서 in 뒤에 위치하여 iterate (반복, 순회)가 가능한 object를 가르킴. __iter__() 라는 special method를 구현하고 있으며, 이를 통해 자신에 대한 iterator object를 반환할 수 있음. __iter__() special

dsaint31.tistory.com


https://ds31x.tistory.com/124

 

[Python] Control Structure and Control Flow

Control structure와 Control Flow란 무엇인가? http://ds31x.blogspot.com/2023/07/basic-control-structures-and-control.html Basic : Control Structures and Control Flow Control Structure 프로그램을 구성하는 statement (=excutable code)들이 실

ds31x.tistory.com

 

'Programming' 카테고리의 다른 글

[ML] Ward’s linkage method  (0) 2023.08.06
[matplotlib] bar chart 그리기 : error bar 포함  (0) 2023.08.01
[PyQt6] QSizePolicy 설정.  (0) 2023.07.03
[Python] Regular Expression : re 요약  (0) 2023.07.03
[Python] str : Overloaded Operators  (0) 2023.07.02
'Programming' 카테고리의 다른 글
  • [ML] Ward’s linkage method
  • [matplotlib] bar chart 그리기 : error bar 포함
  • [PyQt6] QSizePolicy 설정.
  • [Python] Regular Expression : re 요약
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (740)
      • Private Life (13)
      • Programming (56)
        • DIP (104)
        • ML (26)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (351)
        • Signals and Systems (103)
        • Math (172)
        • Linear Algebra (33)
        • Physics (42)
        • 인성세미나 (1)
      • 정리필요. (54)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (1)
        • PET Study 2009 (1)
        • 방사선 장해방호 (4)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    Python
    SIGNAL
    Vector
    function
    fourier transform
    opencv
    인허가제도
    numpy
    random
    Term
    Programming
    Probability
    linear algebra
    math
    signals_and_systems
    Convolution
    검사
    SS
    Optimization
    signal_and_system
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[Python] for statement
상단으로

티스토리툴바