[Python] 위치 인자 모으기(*arg)와 키워드 인자 모으기(**kwargs)

위치 인자 모으기 (*args)

함수의 매개변수에 *을 사용할 때, 이 *은 매개변수에서 위치 인자 변수들을 튜플로 묶어줍니다.

>>> def what_is_args(*args):
... print('Positional argument tuple:', args)

위 함수를 아래처럼 인자 없이 불러오면 *args에는 아무것도 들어 있지 않습니다.

>>> what_is_args()
Positional argument tuple: ()

이번에는 인자를 넣어서 args 튜플을 출력해 보겠습니다.

>>> what_is_args(1, 2, 3, 'data', 'science')
Positional argument tuple: (1, 2, 3, 'data', 'science')

print() 와 같은 함수는 위치 인자를 지정할 때 맨 끝에 *args를 써서 나머지 인자를 모두 취하게 할 수 있습니다.

>>> def printmore(required1, required2, *args):
... print('need this:', required1)
... print('need this too:', required2)
... print('all the rest:', args)
>>> printmore('pen', 'paper', 'watch', 'ipad', 'camera')
need this: pen
need this too: paper
all the rest: ('watch', 'ipad', 'camera')

키워드 인자 모으기 (**kwargs)

키워드 인자를 딕셔너리로 묶기 위해 **를 사용할 수 있습니다. 인자의 이름은 키고, 값은 이 키에 대응하는 딕셔너리 값입니다. 다음 예는 print_kwargs() 함수를 정의해 키워드 인자를 출력합니다.

>>> def print_kwargs(**kwargs):
... print('Keyword arguments:', kwargs)

키워드 인자를 넣어서 함수를 호출해보겠습니다.

>>> def print_kwargs(**kwargs):
... print('Keyword arguments:', kwargs)

>>> print_kwargs(computer='macbook', tablet='ipad', watch='applewatch')
Keyword arguments: {'computer': 'macbook', 'tablet': 'ipad', 'watch': 'applewatch'}

*이 포스트는 Introducing Python
을 보고 연습한 내용을 정리한 것입니다.

[Hexo] YouTube 영상 넣기

Hexo 블로그에 YouTube 영상 넣기

블로그에 유튜브 영상 넣기는 매우 간단합니다. 포스트에 아래 태그를 추가하면 끝.

{% youtube video_id %}

video_id 부분에 아래처럼 동영상 아이디를 적어보겠습니다.

{% youtube KLeiK0whCdY %}

The Piano Guys가 연주한 Ed Sheeran의 PERFECT(Piano Solo Cover)

[Python] Comprehension

1. Comprehension 이란

하나 이상의 iterator로부터 파이썬의 자료구조를 간결하게 만드는 방법을 말합니다. 간단한 구문으로 반복문과 조건 테스트를 결합할 수 있게 해줍니다.

2. list comprehension

1부터 10까지 정수 중 홀수로 된 리스트를 만들어 보겠습니다.

# comprehension을 사용하지 않은 방법
>>>ls = []
>>>for num in range(1, 11):
if num % 2 == 1:
ls.append(num)
>>>ls
[1, 3, 5, 7, 9]
# comprehension을 사용한 방법
>>>ls = [num for num in range(1, 11) if >>>num % 2 == 1]
>>>ls
[1, 3, 5, 7, 9]

다음 코드를 컴프리헨션을 사용해 바꿔보겠습니다.

>>>rows = range(1, 5)
>>>cols = range(1, 3)
>>>for row in rows:
for col in cols:
print(row, col)
1 1
1 2
2 1
2 2
3 1
3 2
4 1
4 2

# comprehension을 사용한 방법

# (row, col) 튜플 리스트를 만들어서 cells 변수에 할당
>>>rows = range(1, 5)
>>>cols = range(1, 3)
>>>cells = [(row, col) for row in rows for col in cols]
# 각 튜플로부터 row와 col만 출력하도록 tuple unpacking
>>>for row, col in cells:
print(row, col)
1 1
1 2
2 1
2 2
3 1
3 2
4 1
4 2

3. dictionary comprehension

딕셔너리도 컴프리헨션이 있습니다. 다음은 문자열 ‘datascience’의 11글자를 반복하면서 글자가 몇 번 나왔는지 세는 코드입니다.

>>>word = 'datascience'
>>>letter_count = {x: word.count(x) for x in word}
>>>letter_count
{'d': 1, 'a': 2, 't': 1, 's': 1, 'c': 2, 'i': 1, 'e': 2, 'n': 1}

4. set comprehension

셋 컴프리헨션도 리스트 컴프리헨션과 딕셔너리 컴프리헨션과 비슷한 모양을 하고 있습니다.

>>> a_set = {num in num in range(1, 6) if num % 3 == 1}
>>> a_set
{1, 4}

5. generator comprehension

제너레이터 컴프리헨션은 제너레이터 객체를 반환합니다. 제너레이터란 이터레이터에 데이터를 제공하는 방법 중 하나입니다.
먼저 제너레이터 컴프리헨션은 다음과 같은 형태를 가집니다.

>>> nums = (num for num in range(1, 6))

제너레이터 객체를 바로 순회할 수 있습니다.

>>> for num in nums:
print(num)
1
2
3
4
5

제너레이터 컴프리헨션에 list() 를 wrapping 하면 리스트 컴프리헨션처럼 만들 수도 있습니다.

>>> nums = (num for num in range(1, 6))
>>> num_list = list(nums)
>>> num_list

*이 포스트는 Introducing Python
을 보고 작성했습니다.

[Python] sort와 sorted

sort()sorted() 의 차이

  • sort() 는 리스트 자체를 정렬함
  • sorted() 는 리스트의 정렬된 복사본을 반환함

예를 들어 다음과 같은 리스트가 있다.

lalaland = ['Mia', 'Sebastian', 'Emily', 'Ryan']

sorted() 를 하면 원래 변수는 변하지 않는다.

>>> sorted_lalaland = sorted(lalaland)
>>> sorted_lalaland
['Emily', 'Mia', 'Ryan', 'Sebastian']
>>> lalaland
['Mia', 'Sebastian', 'Emily', 'Ryan']

반면 sort() 를 하면 lalaland 자체를 정렬된 lalaland 로 바꾼다.

>>> lalaland.sort()
>>> lalaland
['Emily', 'Mia', 'Ryan', 'Sebastian']

정렬 방식은 기본적으로 오름차순이다. 내림차순으로 정렬하려면 인자에 reverse=True 를 넣어주면 된다.

>>> lalaland.sort(reverse=True)
>>> lalaland
['Sebastian', 'Ryan', 'Mia', 'Emily']
© 2019 THE DATASCIENTIST All Rights Reserved.
Theme by hiero