[Python] for문 여러 값 접근하기(index, value 동시에 접근)

숭글·2023년 2월 1일
0
  • enumerate()
  • zip()

enumerate()

for문으로 loop를 돌 때 index와 value을 동시에 접근하고싶을 때가 있다.
외부에서 변수를 만들어서 for문 내에서 증가를 시키고 싶지는 않을 때 python 기본 라이브러리 내에 있는 enumerate()를 사용하면 된다.

enumerate(iterable, start=0)
: enumerate형을 반환한다.

  • iterable은 sequence, iterator등 반복을 지원하는 타입이어야 한다.
  • start를 넘겨줘 시작 인덱스 값을 지정할 수 있다.
  • tuple을 반환한다.

기본 사용법

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))

output >

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
list(enumerate(seasons, start=1))

output >

[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
  • for문을 이용해 동시 접근하기
strs = ['i', 'am', 'hungry', ':-(']

for idx, s in enumerate(strs):
	print(idx, ":", s)

output>

0 : i
1 : am
2 : hungry
3 : :-(

zip()

여러 iterable한 변수에 동시에 접근하기 위해 사용한다.
각 item들을 튜플로 생성해 반환한다.

zip(*iterables, strict=False)

  • 파라미터로 전달된 변수들의 길이가 다를 수도 있다.
    • 기본적으론 가장 짧은 길이의 변수에 맞춰 생성한다.
    • strict로 True를 전달하면 길이가 다를 경우에 ValueError를 발생시킨다. (3.10버전에 추가됐다.)
  • * 연산자를 이용하면 unzip을 할 수 있다.

사용 예제

strs1 = ['i am', 'you are', 'my dog is']
strs2 = ['going home', 'taller than me', 'fatty']

for s1, s2 in zip(strs1, strs2):
	print(s1, s2)

output >

i am going home
you are taller than me
my dog is fatty
  • 길이가 다른 경우
strs1 = ['i am', 'you are', 'my dog is', 'my home is']
strs2 = ['going home', 'taller than me', 'fatty']

for s1, s2 in zip(strs1, strs2):
	print(s1, s2)

output >

i am going home
you are taller than me
my dog is fatty

짧은 쪽에 맞춰 생성한다.

  • 세 개의 인자를 넘긴 경우
strs1 = ['i am', 'you are', 'my dog is', 'my home is']
strs2 = ['going home', 'taller than me', 'fatty']

for idx, s1, s2 in zip(range(10), strs1, strs2):
	print(idx, ":", s1, s2)

output>

0 : i am going home
1 : you are taller than me
2 : my dog is fatty

📖 docs<enumerate>
📖 docs<zip>

profile
Hi!😁 I'm Soongle. Welcome to my Velog!!!

0개의 댓글