반응형

오늘은 Day5인데, 주말이다보니 부여되는 양이 평일에 비해 많아졌다.
오늘도 즐겁게 하자!

Today's Assignment - day 5


오늘의 내용은 Lists와 Loops and List Comprhensions에 대한 내용이다.

Lists에 관한 내용부터 알아보자!

Lists

파이썬의 리스트는 요소값들에 순서가 있다.

primes = [2, 3, 5, 7]

위와 같은 형태로 리스트를 만들 수 있다.
리스트에는 숫자 말고, 문자도 넣을 수 있다.

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

심지어 리스트안에 리스트를 넣을 수도 있다.

hands = [
    ['J', 'Q', 'K'],
    ['2', '2', '2'],
    ['6', 'A', 'K'], # (Comma after the last element is optional)
]
# (I could also have written this on one line, but it can get hard to read)
hands = [['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K']]

그리고, 리스트는 서로다른 숫자와 문자요소를 동시에 가질 수도 있다.

my_favourite_things = [32, 'raindrops on roses', help]
# (Yes, Python's help function is *definitely* one of my favourite things)




Indexing

대괄호를 사용하여 요솟값을 인덱싱 할 수 있다.
리스트의 첫번쨰 요소는 인덱싱하면, 1이아니라 0이다.

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planets[0]

두번째 요소를 인덱싱해보겠다.

planets[1]

이번에는 가장 마지막 요소를 인덱싱 해보겠다.
리스트의 마지막요소는 -1로 인덱싱 할 수 있다. 

planets[-1]

planets[-2]

 

Slicing

이번에는 슬라이싱이다.
리스트의 요소가 만약 10개가 있다고 하자.
그중 앞의 3개만 슬라이싱하고 싶으면 어떻게 해야할까?

planets[0:3]

[0:3]은 첫번째 요소, 두번째 요소, 세번쨰 요소를 슬라이싱한다.

planets[3:]

[3:]이라고 작성하면, 4번째 요소부터 마지막요소까지 슬라이싱된다.

# All the planets except the first and last
planets[1:-1]

[1:-1]은 두번째 요소부터 마지막에서 2번째 요소까지 슬라이싱한다.

[a : -b] 이면 a+1번째 요소부터  뒤에서 -b-1번째 요소까지 슬라이싱된다.
[3:-2]이면 4번째 요소부터 뒤에서 세번째 요소까지 포함하여 슬라이싱된다.

# The last 3 planets
planets[-3:]

그러면 이렇게 슬라이싱하면 어떻게 슬라이싱될까?

이번 정답을 맞췄으면 슬라이싱 인덱스를 완전히 이해한 것이다.


Changing lists

리스트는 요솟값을 변경할 수 있다.
리스트를 수정하는 한 가지 방법은 인덱스 또는 슬라이싱 식에 할당하는 것이다.
예를들어 3번째 요소인 화성의 이름을 변경하려고 한다면 다음과 같이 하면 된다.

planets[3] = 'Malacandra'
planets

이번에는 처음 3개의 행성이름을 줄여보자.

planets[:3] = ['Mur', 'Vee', 'Ur']
print(planets)
# That was silly. Let's give them back their old names
planets[:4] = ['Mercury', 'Venus', 'Earth', 'Mars',]



List functions

파이썬은 리스트 작업에 유용한 몇가지 함수를 제공한다.

lend()은 리스트의 길이를 반환한다.

# How many planets are there?
len(planets)


sorted는 리스트의 요솟값을 정렬시켜서 반환한다.

# The planets sorted in alphabetical order
sorted(planets)


sum은 리스트의 요솟값을 모두 더해준다.

primes = [2, 3, 5, 7]
sum(primes)


max는 최대값을 반환한다.

max(primes)

 

Interlude: objects

파이썬의 모든것은 object(객체)이다. 라는 말을 들어봤을 수도 있다.
간단히 말해서, 객체란 '속성'과 행동으로 이루어진 것이다. 
ex) 자동차는 바퀴 4개, 색깔, 의자, 핸들 등의 속성과, 전진, 후진등의 행동을 가진 객체이다.
파이썬에서 속성은 변수로, 행동은 함수로 나타낸다.

x = 12
# x is a real number, so its imaginary part is 0.
print(x.imag)
# Here's how to make a complex number, in case you've ever been curious:
c = 12 + 3j
print(c.imag)

object에는 함수가 포함될 수 있다. 객체에 부착된 함수를 메서드라고 한다.
예를들어, bit_length라는 메서드가 있다.

x.bit_length

실제로 호출하기위해 괄호를 추가한다.

x.bit_length()

 

help(x.bit_length)

help를 이용하여 도움말을 볼 수 있다.

List methods

list.append는 리스트의 끝에 요소값을 추가하여 리스트를 수정한다.

# Pluto is a planet darn it!
planets.append('Pluto')

만약에 help로 append를 본다고 해보자.

help(planets.append)

help를 호출하려고 하면 python은 "append"라는 변수가 존재하지 않는다고 한다. "append"는 리스트 내에만 존재하며 max또는 len과 같은 기본 제공 함수처럼 독립실행형 이름으로 존재하지 않는다.

append의 결과를 확인해보면,

planets

pluto가 추가된 것을 볼 수 있다.

planets.pop()

planets.pop()를 하면 planets리스트의 마지막 요소를 꺼낼 수 있다. 

planets

pluto가 추출된 것을 확인 할 수 있다. 

 

Searching lists

리스트안에서 Earth는 몇번째 순서인지 list.index방법을 사용해서 인덱스를 가져올 수 있다.

planets.index('Earth')

리스트의 인덱스는 0부터 시작하므로  earth는 3번째 요소이다.

아까 pop로 추출한 Pluto의 인덱스를 찾으려고하면 어떻게 될까?

planets.index('Pluto')

리스트에 Pluto가 없다고 에러가 발생한다.

# Is Earth a planet?
"Earth" in planets

# Is Calbefraques a planet?
"Calbefraques" in planets

 

Tuples

튜플은 리스트와 거의 동일합니다. 하지만 두가지가 다르다.
1. 대괄호 대신 괄호를 사용하여 만든다.

t = (1, 2, 3)
t = 1, 2, 3 # equivalent to above
t

2. 수정할 수 없다(불변)

 

t[0] = 100

 

x = 0.125
x.as_integer_ratio()

이러한 반환값은 다음과 같이 개별적으로 할당할 수 있다.

numerator, denominator = x.as_integer_ratio()
print(numerator / denominator)

마지막으로 두 변수를 교환할 수 있는 전형적인 Stupid Python Trick이다.

a = 1
b = 0
a, b = b, a
print(a, b)

이렇게하면 a와 b가 바뀐다. 


example을 정리한 코드를 공유한다!
https://github.com/mgkim-developer/30-Days-of-ML-with-Kaggle/blob/main/30-days-of-ml-day-5-lists.ipynb

 

GitHub - mgkim-developer/30-Days-of-ML-with-Kaggle: 30 Days of ML with Kaggle

30 Days of ML with Kaggle. Contribute to mgkim-developer/30-Days-of-ML-with-Kaggle development by creating an account on GitHub.

github.com

 

이어서 다음 섹션을 해보자!

Loops

루프는 일부 코드를 반복적으로 실행하는 방법입니다. 예는 다음과 같다.

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planet in planets:
    print(planet, end=' ') # print all on same line

루프를 지정하기 위해서는 아래사항이 필요하다.
사용할 변수 이름
반복할 값의 집합

서로연결하려면 "in"이라는 단어를 사용한다.
리스트말고, 튜플의 요소위에서도 반복할 수 있다.

multiplicands = (2, 2, 2, 3, 3, 5)
product = 1
for mult in multiplicands:
    product = product * mult
product

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

s = 'steganograpHy is the practicE of conceaLing a file, message, image,
or video within another fiLe, message, image, Or video.'
msg = ''
# print all the uppercase letters in s, one at a time
for char in s:
    if char.isupper():
        print(char, end='')

range()

range()는 일련의 숫자를 반환하는 함수다. 이것은 루프를 사용할 때 매우 유용하다.
예를 들어 일부 동작을 5회 반복하려는 경우:

for i in range(5):
    print("Doing important work. i =", i)

 

while loops

파이썬의 또다른 루프유형은 while loop로, 어떤 조건이 충족될 때까지 반복되는 루프다.

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

위의 코드를 for in range를 쓰면, 

squares = []
for n in range(10):
    squares.append(n**2)
squares

if 조건도 추가할 수 있다.

short_planets = [planet for planet in planets if len(planet) < 6]
short_planets

다음은 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

일반적으로 한 줄에 문자를 쓰지만, 세 줄에 걸쳐 분할하면 구조가 더 명확해질 수 있다.

[
    planet.upper() + '!' 
    for planet in planets 
    if len(planet) < 6
]

아래의 표현은 무엇을 나타낼 것 같은가?

[32 for planet in planets]

최소, 최대 및 합과 같은 함수와 결합된 리스트의 이해는, 
여러 줄의 코드가 필요한 문제에 대한 인상적인 한줄 솔루션으로 이루어 질 수 있다.

def count_negatives(nums):
    """Return the number of negative numbers in the given list.
    
    >>> count_negatives([5, -1, -2, 0, 3])
    2
    """
    n_negative = 0
    for num in nums:
        if num < 0:
            n_negative = n_negative + 1
    return n_negative

리스트의 이해를 이용하여 위의 코드를 아래의 코드로 해결하는 방법이다.

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

훨씬 낫지 않은가?
만약, 코드길이를 최소화 하는 데만 신경을 쓴다면 아래의 세번째 솔루션이 더 낫다.

def count_negatives(nums):
    # Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of 
    # Python where it calculates something like True + True + False + True to be equal to 3.
    return sum([num < 0 for num in nums])

최상의 솔루션은 전적으로 주관적이다.
더 적은 코드로 문제를 해결하는 것은 항상 좋지만, 가독성이 중요하다는 점과 명시적인 것이 암묵적인 것보다 좋다는 것을 이해하고 적용해야 한다.

따라서 우리가 프로그램을 만들 때는, 다른사람이 이해하기 쉬운 코드를 선호하는 것이 좋다.

exercise를 수행한 코드를 공유한다!
https://github.com/mgkim-developer/30-Days-of-ML-with-Kaggle/blob/main/30-days-of-ml-day-5-loops.ipynb


 

GitHub - mgkim-developer/30-Days-of-ML-with-Kaggle: 30 Days of ML with Kaggle

30 Days of ML with Kaggle. Contribute to mgkim-developer/30-Days-of-ML-with-Kaggle development by creating an account on GitHub.

github.com

내일도 아마 파이썬 관련된 주제로 2개의 섹션이 부여될 것같은데, 즐겁게 진행해야겠다!
화이팅!

반응형