본문 바로가기
파이썬(Python)

(5) 파이썬(Python)이란? - Loops and List Comprehensions [Hellfer]

by Hellfer 2024. 7. 13.
728x90

https://www.kaggle.com/code/colinmorris/loops-and-list-comprehensions

 

Loops and List Comprehensions

Explore and run machine learning code with Kaggle Notebooks | Using data from No attached data sources

www.kaggle.com

 

위의 글을 참고하여 작성하였습니다.

 

루프는 특정 코드를 여러 번 실행할 수 있게 해주는 프로그래밍 구조입니다.

 

planets = ['Mercury', 'Venus', 'Earth', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planets in planets:
    print(planet, end=' ')

 

Mercuty Venus Earth Jupiter Saturn Uranus Neptune

 

for 루프는 사용할 변수 이름(planets), 반복할 값 세트(planets)를 지정하고 서로 연결할 때는 'in'이라는 단어를 사용합니다.

 

'in'의 오른쪽 객체는 반복을 지원하는 객체이며 리스트 외에도, 튜플의 요소들을 반복할 수 있습니다.

 

multiplicands = (2, 2, 2, 3, 3, 5)
product = 1
# multiplicands를 반복하면서 poduct에 누적 곱하는 반복문
for mult in mutipleicands:
    product = product * mult
    
product

 

360

 

문자열의 각 문자를 반복할 수 있습니다.

 

message = 'Hello'

for char in message:
    print(char)

 

H

e

l

l

o

 


 

range()는 일련의 숫자를 반환하는 함수입니다. 

 

range(start, end)이면 start부터 end-1까지 해당되는 범위를 반환합니다. (start가 0이면 생략해도 무관합니다.)

 

# start=0, end=4까지 반복합니다.
for i in range(5):
    print(f'작업을 {i+1}번 반복합니다.')

 

 

작업을 1번 반복합니다.

작업을 2번 반복합니다.

작업을 3번 반복합니다.

작업을 4번 반복합니다.

작업을 5번 반복합니다.

 

range(start, end, step)은 start부터 end-1까지 해당되는 범위를 반환하고 step값이 숫자 사이의 간격입니다.

 

# 2부터 10까지의 숫자를 2씩 증가시키며 생성
for i in range(2, 11, 2):
    print(i)

 

2

4

6

8

10

 

# 10부터 2까지의 숫자를 -2씩 감소시키며 생성
for i in range(11, 2, -2):
    print(i)

 

10

8

6

4

2

 

while 루프는 특정 조건이 충족될 때까지 반복하는 루프입니다.

 

i = 0
while i < 10 :
    print(i, end=' ')
    i += 1

 

0 1 2 3 4 5 6 7 8 9

 


 

List Comprehension은 간결하고 효율적인 리스트를 생성할 수 있습니다.

 

기본 형식 : [표현식 for 항목 in 반복 가능한 객체]

 

squares = [n ** for n in range(10)]
squares

 

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 

조건부 List Comprehension을 만들면 특정 조건을 만족하는 요소만 포함될 수 있습니다.

 

[표현식 for 항목 in 반복 가능한 객체 if 조건]

 

numbers = [1, 2, 3, 4, 5]

# 짝수만 포함되는 리스트 생성
even_numbers = [number for number in numbers if number % 2 == 0]

print(even_number)

 

[2, 4]

 

문자열의 각 문자를 반복 처리할 수도 있습니다.

 

message = 'Hello'

uppercase_message = [char.upper() for char in message]

print(uppercase_message)

 

['H', 'E', 'L', 'L', 'O']

 

중첩된 루프도 가능합니다.

 

combinations = [(x,y) for x in range(1,4) for y in range(1,3)]

print(combinations)

 

[(1,1), (1,2), (2,1), (2,2), (3,1), (3,2)]

 

중첩된 리스트를 단일 리스트로 평탄화할 수 있습니다.

 

[표현식 for 항목 1 in 반복 가능한 객체 1 for 항목 2 in 반복 가능한 객체 2]

 

nested_list = [[1,2,3], [4,5,6], [7,8,9]]

one_list = [item for sublist in nested_list for item in sublist]

print(one_list)

 

첫 번째로 for sublist in nested_list를 순회합니다.

 

[1,2,3], [4,5,6], [7,8,9]를 차례대로 순회합니다.

 

두 번째로 for item in sublist를 순회합니다.

 

[1,2,3]을 1,2,3으로 [4,5,6]을 4,5,6으로 [7,8,9]을 7,8,9 순서로 one_list에 추가합니다.

 

따라서 one_list는 [1,2,3,4,5,6,7,8,9]가 됩니다.

 


 

 

가독성을 비교하는 세 가지 다른 방식으로 음수의 개수를 세는 함수를 구현해 보겠습니다.

 

def count_negatives(nums):
    """주어진 목록에 있는 음수의 개수를 반환합니다.
    
    >>> count_negatives([5, -1, -2, 0, 3)]
    2
    """
    n_negative=0
    for num in nums:
        if < num:
            n_negative += 1
    return n_negative

 

코드가 길어지고 메모리 낭비가 발생할 수 있습니다.

 

def count_negatives(nums):
    return len([num for num in nums if num < 0])

 

List Comprehension을 사용하여 한 줄로 표현할 수 있습니다.

 

def count_negatives(nums):
    return sum(sum < 0 for num in nums)

 

불리언 값을 이용하여 중간 리스트를 이용하지 생성하지 않고 문제를 해결합니다.

728x90