Python/알면 쓸모있는 잡다한 코드

파이썬 리스트 slicing. for 문 없이 반복 접근 [::] (프로그래머스 5명씩)

joannekim0420 2024. 2. 1. 18:02
728x90
  • Start Index: Not specified, defaults to the beginning of the list (0).
  • Stop Index: Not specified, defaults to the end of the list.
  • Step Size: Not specified, defaults to step size as 1.
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
result_default = my_list[::]  # == my_list[::1]

print(result_default)
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

만약에 5의 배수대로 값들만 갖고 오고 싶을 때는 

result_default = my_list[::5]

 

 

대표적으로, 프로그래머스 https://school.programmers.co.kr/learn/courses/30/lessons/181886

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

def solution(names):
    # return [name for i, name in enumerate(names) if i%5==0]
    return names[::5]

 

for 문을 사용해서 접근해도 되지만, names[::5] 이런식으로 slicing 해서 접근 및 반복 가능