sources :
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
Loops
루프
Loops are a way to repeatedly execute some code. Here's an example:
루프틑 반복적인 코드 실행 방법이다. 예시로
...
The for loop specifies
for 루프 문에서는
the variable name to use (in this case, planet)
the set of values to loop over (in this case, planets)
You use the word "in" to link them together.
사용할 변수명과 (여기서는 planet)
루프를 진행할 변수의 집합 (여기서는 planets)을 표기해야 하는데, 여기서는 'in'이라는 키워드로 둘을 묶어 주었다.
즉 planet in planets # planets라는 리스트 안에 있는 요소를 planet이라는 변수에 넣고 ':' 콜론 아래 명령을 수행하라는 것. 다하고 나면 차례로 다음 요소를 planet에 넣고 반복.
The object to the right of the "in" can be any object that supports iteration. Basically, if it can be thought of as a group of things, you can probably loop over it. In addition to lists, we can iterate over the elements of a tuple:
키워드 'in' 다음에 오는 객체는 iteration (반복)이 가능한 어떤 객체라도 상관이 없다. 어떤 반복적인 것이라면 충분히 이용해서 루프를 돌릴 수 있다.
리스트에 더해서 튜플도 가능하다.
...
You can even loop through each character in a string:
문자열 (string)에 있는 알파벳을 이용한 루프도 가능하다. 문자열은 기본적으로 알파벳을 모은 리스트로 인덱싱과 슬라이싱이 가능하다.
...
range()
range() is a function that returns a sequence of numbers. It turns out to be very useful for writing loops.
range()는 수열을 리턴하며 루프문을 작성하는데 자주 쓰인다.
For example, if we want to repeat some action 5 times:
예를 들어, 5번 반복하고 싶다면 아래와 같이 작성
>>
for i in range(5):
print("Doing important work. i =", i)
while loops
The other type of loop in Python is a while loop, which iterates until some condition is met:
다른 루프 형식으로는 while 문이 있다. 이 루프문은 어떤 특정 조건문(Boolean 식)에 따라 반복된다.
The argument of the while loop is evaluated as a boolean statement, and the loop is executed until the statement evaluates to False.
while 문의 인자(argument)는 조건문(boolean statement)으로 판별된다. 조건문이 참인 경우는 아래가 실행되고 거짓이면 실행되지 않고 스킵된다.
List comprehensions
List comprehensions are one of Python's most beloved and unique features. The easiest way to understand them is probably to just look at a few examples:
리스트해석은 파이썬의 가장 자랑할만한 특징이다. 일단 아래 몇가지 예를 살펴보기 바란다.
>>
squares = [n**2 for n in range(10)]
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Here's how we would do the same thing without a list comprehension:
만약 리스트해석(List Comprehension)없이 동일한 작업을 하려면 아래와 같은 코딩이 필요하다.
>>
squares = []
for n in range(10):
squares.append(n**2)
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
We can also add an if condition:
여기에 우리는 if 문을 더할 수도 있다.
>>
short_planets = [planet for planet in planets if len(planet) < 6]
short_planets
['Venus', 'Earth', 'Mars']
#If you're familiar with SQL, you might think of this as being like a "WHERE" clause
#만약 SQL(데이터베이스용 언어)에 익숙하다면 위의 if 문 용법이 WHERE 문과 유사하다고 느낄 것이다.
Here's an example of filtering with an if condition and applying some transformation to the loop variable:
아래는 if문과 루프문 변수에 약간의 변형을 줘서 필터링을 거는 방법을 보여준다.
(#필터링이란 필요한 변수만 걸러내는 과정)
>>
# str.upper() returns an all-caps version of a string
loud_short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6]
loud_short_planets
['VENUS!', 'EARTH!', 'MARS!']
People usually write these on a single line, but you might find the structure clearer when it's split up over 3 lines
보통 위의 동작을 한 문장으로 나타내지만 아래와 같이 3개의 문장으로 나눈다면 좀 더 의미가 명확해 보일 것이다.
[
planet.upper() + '!'
for planet in planets
if len(planet) < 6
]
['VENUS!', 'EARTH!', 'MARS!']
#Continuing the SQL analogy, you could think of these three lines as SELECT, FROM, and WHERE
#SQL과의 유사성을 계속 찾는다면 아마 이러한 용법은 (SQL의) SELECT, FROM and WHERE가 결합된 쿼리문과 유사하게 생각될 것이다.
The expression on the left doesn't technically have to involve the loop variable (though it'd be pretty unusual for it not to). What do you think the expression below will evaluate to? Press the 'output' button to check.
위 문장의 왼쪽편은 기술적으로는 루프문의 안에 없다고 봐야 한다. 조금 이상한게 당연하다. 아래 예시문을 실행시켜 보자.
List comprehensions combined with functions like min, max, and sum can lead to impressive one-line solutions for problems that would otherwise require several lines of code.
리스트해석(List Comprehension)은 min, max, sum 등의 함수와 같이 사용하여 3라인 이상이어야 할 문장을 한줄로 표현할수 있게 해준다.
For example, compare the following two cells of code that do the same thing.
예를 들어, 아래 코드를 비교해 봐라. 두 코드는 모두 동일한 작업을 하고 있다.
... 생략...
Here's a solution using a list comprehension:
만약 리스트해석(List Comprehension)을 사용한다면,
...생략...
Well if all we care about is minimizing the length of our code, this third solution is better still!
만약 코딩 길이를 최소화 하고 싶다면 이 방법은 여전히 유효하다.
...생략..
Which of these solutions is the "best" is entirely subjective. Solving a problem with less code is always nice, but it's worth keeping in mind the following lines from The Zen of Python:
위 두 방식중에 어떤것이 최선의 방법인가 하는 것은 전적으로 주관적이다. (당신한테 달렸다.) 가능한 적은 코딩 길이로 문제를 해결한다는 것은 좋은 일이지만 항상 다음과 같은 파이썬의 격언을 잊지 말아야 한다.
Readability counts.
Explicit is better than implicit.
해석이 가능한 것은 중요하다.
명시적인 것이 함축적인 것보다 낫다.
(#즉 코딩은 사람이 읽어서 해석이 쉬워야 하고 명시적으로 표현하는 것이 여러 중의적으로 해석될 수 있는 것보다 낫다는 것이다.)
So, use these tools to make compact readable programs. But when you have to choose, favor code that is easy for others to understand.
...다른 사람이 이해하기 쉬운 것을 좋은 코드를 택해야 한다..
[파이썬7강] Working with External Libraries (0) | 2025.01.06 |
---|---|
[파이썬 6강] 스트링과 딕셔너리 (0) | 2025.01.03 |
[파이썬 제4강] Lists (0) | 2024.12.30 |
[파이썬3강]Booleans (0) | 2024.12.27 |
[파이썬2강] Functions and getting help-Tutorial (1) | 2024.12.26 |