지난 포스팅에서는 파이썬 프로그래밍에 들어가기에 앞서 파이썬이 어떻게 참(True), 거짓(False)을 평가, 판단하는지에 대한 기본 문법을 알아보았습니다. 


이번 포스팅부터는 파이썬 프로그램의 흐름을 제어(Python progmram flow control)하는 방법에 대해서 몇 개 포스팅으로 나누어서 소개를 하겠습니다. 


파이썬 프로그램 흐름 제어에서 알아야 할 큰 2가지 뼈대가 있다면 


- (1) 조건이 참(True), 거짓(False)인지에 따라 프로그램 흐름을 나누어 주는 분기문(Branch statements)

       : if statements

       : if, else statements

       : if, elif, else statements

       : nested if statements


- (2) 조건이 참이거나 순서열의 끝까지 반복, 중단하게 해주는 반복문

       : while

       : for

       : continue, break


가 있습니다. 


이번 포스팅에서는 먼저 if, elif, else 분기문(Branch statement)에 대해서 알아보겠습니다. 



[ 파이썬 프로그램 흐름 제어 (Python program flow control) ]






먼저 if, else 분기문에서 사용하는 용어를 간단히 짚어보고 넘어가겠습니다. 


  • if 조건문에는 참(True), 거짓(False)을 평가할 수 있는 조건을 써주고, 마지막에는 콜론(:)을 붙여줍니다.
  • if 조건문이 거짓이면 'else:' 조건문으로 프로그램 흐름이 넘어가게 되며, 역시 마지막 부분에 콜론(:)을 붙여줍니다. 
  • if, else 조건문 아래의 컴퓨터에게 시킬 일을 적어놓은 부분은 'Code Block'라고 합니다. 
  • Code Block 은 '들여쓰기(indentation)'를 해서 구분을 해줍니다. 보통 space bar로 4칸 사용합니다. 
    (R, Java, C 등은 중괄호 { } 를 사용)


[ 파이썬 if, else 분기문 예시 (example of Python if, else branch statement) ]




이제 파이썬의 if, else 분기문을 가지고 간단한 프로그램을 하나 짜보도록 하겠습니다. 


 (1) 조건이 1개 일 때 if, else 분기문 (if, else branch statement with 1 condition)


파이썬이 해야 하는 일의 흐름은, 

  • (1-1) 파이썬 시험 점수를 입력받아서

  • (1-2) 만약 파이썬 시험 점수가 80점 이상이면 (if 조건문 True)
    "당신의 파이썬 점수는 xx점입니다. 축하합니다. 파이썬 시험을 통과하였습니다. :-)"
    를 출력하고, 종료. 

  • (1-3) 만약 파이썬 시험 점수가 80점 이상이 아니면 (if 조건문 False)
    "당신의 파이썬 점수는 xx점입니다. 파이썬 시험을 낙제했습니다. 공부 더 하세요. T_T"
    를 출력하고 종료. 

        [ Flow Diagram ]



위의 프로그램 흐름을 if, else 분기문을 사용해서 파이썬 프로그래밍을 해보면 아래와 같습니다. 



# (1) if, else statement


print('Put your Python test score : ')


py_score = int(input())


if py_score >= 80:

    

    print('Your Python score is {0}'.format(py_score))

    print('Congratulations! You passed Python test. :-)')

    

else:

    

    print('Your Python score is {0}'.format(py_score))

    print('You failed Python test. Study more! T_T')

 



아래에 파이썬 시험 점수가 90점일 때와 70점일 때 원하는 메시지대로 출력을 제대로 해주는지 시험해 보겠습니다. 



Put your Python test score :

90


Your Python score is 90

Congratulations! You passed Python test. :-)

 



Put your Python test score :

70


Your Python score is 70

You failed Python test. Study more! T_T

 



if 와 else 분기절의 마지막에 콜론(colon, :)을 실수로 빼먹으면 'SyntaxError: invalid syntax' 에러가 발생합니다. 



# If you miss colon(:) at the end, then 'SyntaxError: invalid syntax'

In [3]: print('Put your Python test score : ')

    ...:

    ...: py_score = int(input())

    ...:

    ...: if py_score >= 80 # Oops! Syntax Error due to no colon(:)

    ...:

    ...: print('Your Python score is {0}'.format(py_score))

    ...: print('Congratulations! You passed Python test. :-)')

    ...:

    ...:

    ...: else:

    ...:

    ...: print('Your Python score is {0}'.format(py_score))

    ...: print('You failed Python test. Study more! T_T')

    ...:

File "<ipython-input-18-b2c00ee4ee98>", line 5

if py_score >= 80 # Oops! Syntax Error due to no colon(:)

^

SyntaxError: invalid syntax

 




다음으로, 조건이 2개 이상일 때 if, elif, else 분기문 사용하는 법을 알아보겠습니다. elif 는 else if 의 줄임말로 보면 되겠습니다. 


 (2) 조건이 2개 일 때 if, elif, else 분기문 

      (if, elif, else branch statement with multiple condition expressions)


파이썬 시험 점수는 0점 ~ 100점 사이의 정수만 가능하고, 0점~100점 사이의 정수를 벗어나면 (예: -50점, 150점) '점수를 잘못입력했습니다'라는 안내 메시지를 출력하는 것으로 프로그램 코드를 좀더 똑똑하게 짜보겠습니다. 

  • (2-1) 파이썬 시험 점수를 입력받아서

  • (2-2) 만약 파이썬 시험 점수가 '80점 이상 ~ 100점 이하' 이면 
    "당신의 파이썬 점수는 xx점입니다. 축하합니다. 파이썬 시험을 통과하였습니다. :-)"를 출력하고, 종료. 

  • (2-3) 만약 파이썬 시험 점수가 '80점 이상 ~ 100점 이하'가 아니면서, '0점 이상 ~ 80점 미만'이면 
    "당신의 파이썬 점수는 xx점입니다. 파이썬 시험을 낙제했습니다. 공부 더 하세요. T_T"를 출력하고 종료. 

  • (2-4) 만약 파이썬 시험 점수가 '80점 이상 ~ 100점 이하'도 아니고, '0점 이상 ~ 80점 미만'도 아니면 
    "파이썬 시험 점수를 잘못 입력하였습니다" 를 출력하고 종료. 


       [ Flow Diagram ]




위의 (2-2) 프로그램 흐름을 파이썬 코드로 짜보면 아래와 같습니다.  if 조건문 안에 if 조건문을 중첩해서 쓸 수도 있구요, and, or 논리 연산자를 같이 쓸 수도 있습니다. 


# (2) if, elif, else statement


print('Put your Python test score : ')


py_score = int(input())


if py_score >= 80 and py_score <= 100:

    

    print('Your Python score is {0}'.format(py_score))

    print('Congratulations! You passed Python test')

    

elif py_score >= 0 and py_score < 80:

    

    print('Your Python score is {0}'.format(py_score))

    print('You failed Python test. Study more!')

    

else:

    

    print('You put the wrong score.')

 



파이썬 점수로 150점 (<- 잘못 입력), 90점(<- 시험 통과), 60점(<- 시험 낙제), -50점(<- 잘못 입력) 을 각 각 입력해보겠습니다. 



Put your Python test score : 

150


You put the wrong score.

 



Put your Python test score : 

90


Your Python score is 90

Congratulations! You passed Python test

 



Put your Python test score : 

60


Your Python score is 60

You failed Python test. Study more!

 



Put your Python test score : 

-50


You put the wrong score.

 




 (3) if 조건문 안에 if 조건문을 중첩해서 프로그래밍 하기 (nested if statements)


위의 (2)번 프로그램 흐름을 nested if statements를 사용해서 아래에 구현해 보았습니다. 위의 (2)번 if, elif, else 보다 더 복잡하고 코드도 길군요. 특히, nested if statements 를 사용할 때는 들여쓰기(indentation) 할 때 유의해야 합니다.  Spyder나 Pycharm 같은 IDE 의 Editor 창을 사용하면 자동으로 들여쓰기를 해줘서 실수를 방지하는데 도움이 됩니다. 



# (3) nested if statements

print('Put your Python test score : ')


py_score = int(input())


if py_score <= 100:

    if py_score >= 80:       

        print('Your Python score is {0}'.format(py_score))

        print('Congratulations! You passed Python test. :-)')

    

    else:       

        if py_score < 80:

            if py_score > 0:

                print('Your Python score is {0}'.format(py_score))

                print('You failed Python test. Study more! T_T')

                

            else:                

                print('You put the wrong score.')

        

else:    

    print('You put the wrong score.')

 



프로그램 흐름 제어 코드를 잘 짠건지 한번 시험을 해볼까요?  150점 (<- 잘못 입력), 90점 (<- 시험 통과), 60점 (<- 시험 낙제), -50점 (<- 잘못 입력)을 각 각 입력해보겠습니다.  아래 결과를 보니 파이썬 프로그램 코드를 제대로 짰네요. ^^



Put your Python test score : 

150


You put the wrong score.

 



Put your Python test score : 

90


Your Python score is 90

Congratulations! You passed Python test. :-)

 



Put your Python test score : 

60


Your Python score is 60

You failed Python test. Study more! T_T

 



Put your Python test score : 

-50


You put the wrong score.

 



많은 도움이 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. 


다음 포스팅에서는 반복문(Loop statement)에 대해서 알아보겠습니다. 



728x90
반응형
Posted by Rfriend
,

Python 으로 if 를 활용한 분기문이나 for, while 을 활용한 반복문 프로그래밍에 들어가기에 앞서서, if, for, while 프로그래밍의 기초 지식이 되는 블리언 형식에 대해서 알아보겠습니다. 


이번 포스팅은 어려운건 없구요, 그냥 편안하게 몸풀기 (머리 풀기?) 정도로 읽어보면 좋겠습니다. 

(not 논리 연산자가 살짝 헷갈리기는 합니다만, 전반적으로 매우 쉬움)


블리언 형식(Boolean type)참(True), 거짓(False) 의 두 개 값을 가지는 자료형을 말합니다. 



# (1) Boolean Type

In [1]: a = 2 > 1


In [2]: a

Out[2]: True


In [3]: b = 2 < 1


In [4]: b

Out[4]: False


In [5]: type(a)

Out[5]: bool

 


불리언 값이 (1) 조건문, (2) 논리 연산자, (3) 비교 연산자에서 어떤 경우에 참(True)이고, 어떤 경우에 거짓(False) 인지에 대해서 짚고 넘어가 보겠습니다. 



[ 파이썬 참/거짓 불리언 형식 (Python Boolean Type ]





 (1) 조건문에서의 참, 거짓 (True, False in Conditional statements)


프로그래밍의 조건문에서 참, 거짓을 판단할 때 블리언 False, None, 숫자 0, 비어있는 리스트, 비어 있는 튜플, 비어있는 사전 자료형의 경우에 False 로 판단을 합니다. 


반대로 블리언 True, not None, 0이 아닌 숫자, 값이 있는 리스트, 값이 있는 튜플, 값이 있는 사전 자료형의 경우 True 로 판단을 하구요. 


자료형마다 값이 없이 비어있으면 거짓, 값을 가지고 있으면 참이라고 파이썬은 판단한다는게 재미있습니다. ^^


각 경우 마다 bool() 함수를 사용해서 파이썬이 참(True)과 거짓(False) 중에 어떻게 판단을 하는지 예를 들어서 살펴보겠습니다. 



# (1-1) Boolean False, True

In [6]: bool(False) # False

Out[6]: False


In [7]: bool(True) # True

Out[7]: True

 



# (1-2) None is False

In [8]: bool(None) # False

Out[8]: False

 



# (1-3) Number 0, 0.00 is False

In [9]: bool(0) # False

Out[9]: False


In [10]: bool(0.00) # False

Out[10]: False


In [11]: bool(5) # True

Out[11]: True

 



# (1-4) blank List [] is False

In [12]: bool([]) # False

Out[12]: False


In [13]: bool(['a', 'b']) # True

Out[13]: True

 



# (1-5) blank Tuple () is False

In [14]: bool(()) # False

Out[14]: False

In [15]: bool(('a', 'b')) # True

Out[15]: True

 



# (1-6) blank Dictionary {} is False

In [16]: bool({}) # False

Out[16]: False

In [17]: bool({'a': 'b'}) # True

Out[17]: True

 




  (2) 논리 연산자에서 참, 거짓 (True, False in Logical operators) : not, and, or


파이썬의 논리 연산자(Logical operators)에는 피연산자를 부정하는 not, 두 피연산자 간의 논리곱을 수행하는 and, 두 연산자 간의 논리합을 수행하는 or 의 3가지가 있습니다. 



(2-1) 피연산자를 부정하는 'not' 논리 연산자 


위에서 소개한 조건문에서의 참, 거짓에 not 연산자를 붙이면 참이 거짓으로 바뀌고, 거짓은 참으로 바뀌게 됩니다. 



# (2-1) 피연산자 부정 'not' logical operator


In [18]: not True # False

Out[18]: False


In [19]: not False # True

Out[19]: True

 



숫자 '0'은 거짓(False)라고 했으므로 앞에 부정 연산자 not 이 붙으면 참(True)이 됩니다. 반면, '0'이 아닌 숫자는 참(True)이라고 했으므로 앞에 not 이 붙으면 거짓(False)으로 바뀝니다. 



In [20]: not 0 # True

Out[20]: True


In [21]: not 5 # False

Out[21]: False

 



None 은 거짓(False)라고 했으므로 not None은 참(True)로 평가합니다. 



In [22]: not None # True

Out[22]: True

 



비어있는 문자열, 리스트, 튜플, 사전은 거짓(False)으로 평가한다고 했으므로, 피연산자를 부정하는 not 이 붙으면 참(True)으로 바뀌게 됩니다. 



In [23]: not '' # denial of blank String -> True

Out[23]: True


In [24]: not [] # denial of blank List -> True

Out[24]: True


In [25]: not () # denial of blank Tuple -> True

Out[25]: True


In [26]: not {} # denial of blank Dictionary -> True

Out[26]: True

 



반대로, 문자열, 리스트, 튜플, 사전에 값이 들어있는 경우 참(True)으로 평가한다고 했으므로, 피연산자를 부정하는 not이 붙으면 거짓(False)이 됩니다.  위와 아래의 비어있는 자료형에 not 붙인 경우와 값이 있는 자료형에 not 붙인 경우의 참, 거짓이 처음엔 좀 직관적으로 와닿지가 안던데요, 자꾸 보니깐 그러려니 하게 되네요. ^^'



In [27]: not 'ab' # False

Out[27]: False


In [28]: not ['a', 'b'] # False

Out[28]: False


In [29]: not ('a', 'b') # False

Out[29]: False


In [30]: not {'a' : 'b'} # False

Out[30]: False

 




(2-2) 두 피연산자 간의 논리곱을 수행하는 and 논리 연산자


두 개의 피연산자가 모두 참(True and True)이면 True 이며, 두 피연산자 값 중에서 하나라도 거짓(False)이 있으면 거짓(False) 으로 판단합니다. 



# (2-2) 논리곱 'and' logical operator

In [31]: True and True # True

Out[31]: True


In [32]: True and False # False

Out[32]: False


In [33]: False and True # False

Out[33]: False

 

In [34]: False and False # False

Out[34]: False





(2-3) 두 피연산자 간의 논리합을 수행하는 or 논리 연산자


두 피연산자 중에서 한 개(True or False, False or True)나 혹은 두개 모두(True or True) 이라도 참(True)이면 참으로 평가합니다. 



# (2-3) 논리합 'or' logical operator

In [35]: True or True # True

Out[35]: True


In [36]: True or False # True

Out[36]: True


In [37]: False or False # False

Out[37]: False

 




  (3) 비교 연산자에서의 참, 거짓 (True, False in Comparison operators) : ==, !=, >, >=, <, <=


(3-1) == 비교 연산자


두 피연산자의 값이 같으면 참(True), 서로 다르면 거짓(False)으로 평가



# (3) Comparison(Relational) operators


In [39]: a = 1; b = 2; c = 2 # input data



# (3-1) == : If the values of two operands are equal, then the condition becomes true


In [40]: a == b # False

Out[40]: False


In [41]: b == c # True

Out[41]: True

 



(3-2) != 비교 연산자


두 피연산자의 값이 같지 않으면 참(True), 같으면 거짓(False)으로 평가 (음... 좀 헷갈리지요. ^^;)



In [39]: a = 1; b = 2; c = 2 # input data

# (3-2) != : If values of two operands are not equal, then condition becomes true

In [42]: a != b # True

Out[42]: True


In [43]: b != c # False

Out[43]: False

 



(3-3) > 비교 연산자


: 왼쪽의 피연산자 값이 오른쪽의 피연산자 값보다 크면 참(True), 아니면 거짓(False)



In [39]: a = 1; b = 2; c = 2 # input data


# (3-3) > : If the value of left operand is greater than the value of right operand, 

# then condition becomes true


In [44]: a > b # False

Out[44]: False


In [45]: b > a # True

Out[45]: True


In [46]: b > c # False

Out[46]: False

 



(3-4) >= 비교 연산자


왼쪽의 피연산자 값이 오른쪽의 피연산자 값보다 크거나 같으면 참(True), 아니면 거짓(False)



In [39]: a = 1; b = 2; c = 2 # input data


# (3-4) >= : If the value of left operand is greater than or equal to the value of right operand, 

# then condition becomes true


In [47]: a >= b # False

Out[47]: False


In [48]: b >= a # True

Out[48]: True


In [49]: b >= c # True

Out[49]: True

 



(3-5) < 비교 연산자


왼쪽 피연산자의 값이 오른쪽 피연산자의 값보다 작으면 참(True), 아니면 거짓(False)



In [39]: a = 1; b = 2; c = 2 # input data

# (3-5) < : If the value of left operand is less than the value of right operand, 

# then condition becomes true


In [50]: a < b # True

Out[50]: True


In [51]: b < a # False

Out[51]: False


In [52]: b < c # False

Out[52]: False

 



(3-6) <= 비교 연산자


왼쪽 피연산자의 값이 오른쪽 피연산자의 값보다 작거나 같으면 참(True), 아니면 거짓(False)



In [39]: a = 1; b = 2; c = 2 # input data


# (3-6) <= : If the value of left operand is less than or equal to the value of right operand,
# then condition becomes true


In [53]: a <= b # True

Out[53]: True


In [54]: b <= a # False

Out[54]: False


In [55]: b <= c # True

Out[55]: True

 



많은 도움이 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^


다음번 포스팅에서는 if ~ else 분기문(Branch statement)에 대해서 알아보겠습니다. 



728x90
반응형
Posted by Rfriend
,

파이썬(Python)에는 다양한 형태의 다수의 데이터를 다룰 수 있는 자료형으로 리스트(Lists), 튜플(Tuples), 사전(Dictionary) 등이 있습니다. 


지난번 포스팅에서는 사전(Python Dictionary) 자료형의 생성, 삭제, 기본 연산자에 대해서 소개하였습니다.  이번 포스팅에서는 지난번에 이어서, 사전 자료형의 내장 함수 및 메소드(Dictionary built-in functions and methods)에 대해서 알아보겠습니다. 


사전 자료형은 키와 값의 쌍(pair of Key and Value)으로 이루어져 있는 형태에 맞게 이에 특화된 메소드들이 있습니다. 



[ 파이썬 사전 자료형의 내장 함수 및 메소드 (Python Dictionary built-in functions and methods) ]






1. 파이썬 사전 자료형의 내장 함수 (Python Dictionary built-in functions)


 1-1. len(dict): 사전의 총 길이 (total length of Dictionary)



# 1-1. len(dict) : Gives the total length of the dictionary

>>> dict_1 = {'name' : 'R Friend', 

...           'region' : 'Busan, Korea', 

...           'phone' : '010-123-9876', 

...           'age' : 30}

>>> dict_1

{'name': 'R Friend', 'region': 'Busan, Korea', 'phone': '010-123-9876', 'age': 30}

>>> len(dict_1)

4

 




 1-2. str(dict): 사전을 문자열로 반환 (string representation of a Dictionary)



# 1-2. str(dict) : Produces a printable string representation of a dictionary

>>> str(dict_1)

"{'name': 'R Friend', 'region': 'Busan, Korea', 'phone': '010-123-9876', 'age': 30}"





 1-3. type(variable): 입력 변수의 유형 반환 (returns the type of the passed variable)



# 1-3. type() : Returns the type of the passed variable

>>> type(dict_1)

<class 'dict'>

 





2. 파이썬 사전 자료형의 메소드 (Python Dictionary methods)


 2-1. dict.keys(): 사전의 키 목록



# 2-1. dict.keys(): Returns a list of all the available keys in the dictionary

>>> dict_2 = {'key1' : 123, 

...           'key2' : 'abc', 

...           'key3' : (1, 2, 3)}

>>> 

>>> dict_2

{'key1': 123, 'key2': 'abc', 'key3': (1, 2, 3)}

>>> 

>>> dict_2.keys()

dict_keys(['key1', 'key2', 'key3'])

 




 2-2. dict.values(): 사전의 값 목록



# 2-2. dict.values(): Returns a list of all the values available in the dictionary

>>> dict_2 = {'key1' : 123, 

...           'key2' : 'abc', 

...           'key3' : (1, 2, 3)}

>>> 

>>> dict_2

{'key1': 123, 'key2': 'abc', 'key3': (1, 2, 3)}

>>> 

>>> dict_2.values()

dict_values([123, 'abc', (1, 2, 3)])

 




 2-3. dict.items(): 사전의 (키, 값) 튜플 목록 



# 2-3. dict.items(): Returns a list of dict's (key, value) tuple pairs

>>> dict_2 = {'key1' : 123, 

...           'key2' : 'abc', 

...           'key3' : (1, 2, 3)}

>>> 

>>> dict_2

{'key1': 123, 'key2': 'abc', 'key3': (1, 2, 3)}

>>> 

>>> dict_2.items()

dict_items([('key1', 123), ('key2', 'abc'), ('key3', (1, 2, 3))])

 




 2-4. dict.clear(): 사전의 모든 {키, 값} 셋 제거



# 2-4. dict.clear() : Removes all items from the dictionary

>>> dict_2 = {'key1' : 123, 

...           'key2' : 'abc', 

...           'key3' : (1, 2, 3)}

>>> 

>>> dict_2

{'key1': 123, 'key2': 'abc', 'key3': (1, 2, 3)}

>>> 

>>> dict_2.clear()

>>> dict_2

{}

 




 2-5. dict.copy(): 사전의 {키 : 값} 셋 복사



# 2-5. dict.copy(): Returns a copy of the dictionary

>>> dict_2 = {'key1' : 123, 

...           'key2' : 'abc', 

...           'key3' : (1, 2, 3)}

>>> 

dict_2

>>> {'key1': 123, 'key2': 'abc', 'key3': (1, 2, 3)}

>>> 

>>> dict_3 = dict_2.copy()

>>> dict_3

{'key1': 123, 'key2': 'abc', 'key3': (1, 2, 3)}

 




 2-6. dict.fromkeys(seq, value): seq, value 셋으로 신규 사전 생성



# 2-6. dict.fromkeys(): Creates a new dictionary with keys from seq and values set to value

>>> seq = ('key1', 'key2', 'key3')

>>> 

>>> dict_4 = dict.fromkeys(seq)

>>> dict_4

{'key1': None, 'key2': None, 'key3': None}

>>> 

>>> dict_4 = dict.fromkeys(seq, 123)

>>> dict_4

{'key1': 123, 'key2': 123, 'key3': 123}

 




2-7. dict.get(key, default=None): 키에 할당된 값 반환



# 2-7. dict.get(key, default=None): Returns a value for the given key

>>> dict_2 = {'key1' : 123, 

...           'key2' : 'abc', 

          'key3' : (1, 2, 3)}

... >>> 

>>> dict_2

{'key1': 123, 'key2': 'abc', 'key3': (1, 2, 3)}

>>> 

>>> dict_2.get('key1', 'No_Key')

123

>>> dict_2.get('key5', 'No_Key') # If key is not available then returns 'No_Key'

'No_Key'

>>> dict_2.get('key5') # If key is not available then returns default value None

 




2-8. dict.setdefault(key, default=None) : 키에 할당된 값 반환


dict.get()과 유사합니다. 



# 2-8. dict.setdefault(key, default=None): Returns the key value available in the dictionary

>>> dict_2 = {'key1' : 123, 

...           'key2' : 'abc', 

...           'key3' : (1, 2, 3)}

>>> 

>>> dict_2

{'key1': 123, 'key2': 'abc', 'key3': (1, 2, 3)}

>>> 

dict_2.setdefault('key1', 'No-Key')

>>> 123

>>> dict_2.setdefault('key5', 'No_Key') 

'No_Key'

>>> dict_2.setdefault('key6', None)

 




2.9. dict.update(dict2): 기존 사전에 새로운 사전 dict2 추가



# 2-9. dict.update(dict2): Adds dictionary dict2's key-values pairs into dict

>>> dict_5 = {'key1' : 12, 

...           'key2' : 34}

>>> dict_5

{'key1': 12, 'key2': 34}

>>> 

>>> dict_6 = {'key3' : 56}

>>> 

>>> dict_5.update(dict_6)

>>> dict_5

{'key1': 12, 'key2': 34, 'key3': 56}

 



드디어 파이썬의 5가지 자료형인 숫자(Number), 문자열(String), 리스트(List), 튜플(Tuple), 그리고 사전(Dictionary)에 대한 생성, 기본 사용법, 내장함수 및 메소드에 대한 소개를 마쳤습니다. 


가장 기본이 되는 것이고 매우 매우 중요한 것이다 보니 블로그에 한번 정리를 해야지, 해야지... 하다가도 numpy 랑 pandas 먼저 포스팅하고.... 한참이 지나서야 기본이 되는 자료구조에 대해서는 이제서야 포스팅을 하게 되었네요.  밀린 숙제 끝낸 기분이라 홀가분하고 좋네요. ^^


많은 도움이 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^


728x90
반응형
Posted by Rfriend
,

다양한 다수의 데이터를 다룰 수 있는 파이썬의 자료형으로 리스트(List), 튜플(Tuple), 사전(Dictionary) 자료형이 있다고 했습니다. 


그중에서 리스트와 튜플은 이전 포스팅에서 소개를 했구요, 이번 포스팅에서는 마지막으로 사전(Dictionary)에 대해서 알아보겠습니다. 


사전(Dictionary) 자료형은 마치 영한사전이 {영어단어 : 한글 뜻} 과 같이 서로 짝꿍을 이루어서 구성이 되어있는 것처럼, {키(Key) : 값(Value)} 이 콜론( :, colon)으로 구분이 되어서 쌍(pair)을 이루고 있고, 중괄호( { }, curly braces)로 싸여져 있는 자료형입니다. 


사전(Dictionary) 자료형의 키(Key)는 튜플처럼 변경 불가능(immutable)하고 유일한 값(unique)을 가지며, 값(Value)은 리스트처럼 변경이 가능(mutable) 합니다. 사전형은 키를 hashing (Dictionary as a Hash table type)해놓고 있다가 키를 사용하여 값을 찾으려고 하면 매우 빠른 속도로 값을 찾아주는 매우 효율적이고 편리한 자료형입니다. 



[ 파이썬의 5가지 자료형 (Python's 5 Data Types) ]





 1. 사전 {키 : 값} 생성: {Key1 : Value1, Key2 : Value2, ...}


{Key : Value} 를 콜론(:)으로 구분해서 쌍을 이루어주며, 다수 개의 {Key:Value}를 하나의 사전에 묶으려면 콤마(,)로 구분해서 이어주고 중괄호({ }, curly braces) 로 싸주면 됩니다.



# making Dictionary with {Key1 : Value1, Key2 : Value2, ...}

>>> dict_1 = {'name' : 'Python Friend', 

...           'region' : 'Busan, Korea', 

...           'phone' : '010-123-9876', 

...           'age' : 30}

>>> dict_1

{'name': 'Python Friend', 'region': 'Busan, Korea', 'phone': '010-123-9876', 'age': 30}

 



위의 예시처럼 한번에 {Key1 : Value1, Key2 : Value2, ...} 과 같이 키, 값 쌍을 한꺼번에 나열 할 수도 있구요, 아래의 예시처럼 먼저 { } 로 빈 사전 자료를 만들어놓은 다음에 dict[Key] = 'Value' 방식으로 하나씩 추가해나가는 방법도 있습니다. 



# making a blank Dictionary { } first, and adding {Key : Value} pairs step by step using [Key] indexing

>>> dict_2 = {} # blank Dictionary

>>> dict_2['name'] = 'R Friend'

>>> dict_2['region'] = 'Seoul, Korea'

>>> dict_2['phone'] = '02-123-4567'

>>> dict_2['age'] = 20

>>> dict_2

{'name': 'R Friend', 'region': 'Seoul, Korea', 'phone': '02-123-4567', 'age': 20}

 




  2. 사전의 키 별 값 확인 (Accessing Values per Key in Dictionary): dict[Key]



# Accessing Values per Key in Dictionary

>>> dict_1 = {'name' : 'Python Friend', 

...           'region' : 'Busan, Korea', 

...           'phone' : '010-123-9876', 

...           'age' : 30}

>>> dict_1['name']

'Python Friend'

>>> dict_1['region']

'Busan, Korea'

 



만약 사전(Dictionary)에 없는 키(Key)로 값(Value)을 확인하려고 하면 KeyError가 발생합니다. 



# KeyError when there is no 'Key' in a Dictionary

>>> dict_1 = {'name' : 'Python Friend', 

...                   'region' : 'Busan, Korea', 

...                   'phone' : '010-123-9876', 

...                   'age' : 30}

>>> dict_1

{'name': 'Python Friend', 'region': 'Busan, Korea', 'phone': '010-123-9876', 'age': 30}

>>> dict_1['address'] # KeyError due to no 'address' Key in dict_1

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

KeyError: 'address'

 




  3. 사전 갱신 (Updating Dictionary)


기존의 {키:값} 쌍의 값을 갱신하는 경우와, 새로운 {키:값} 쌍을 추가하는 방법이 있습니다. 



# Updating Dictionary : (1) updating an existing entry, (2) adding a new entry

>>> dict_1 = {'name' : 'Python Friend'

...           'region' : 'Busan, Korea', 

...           'phone' : '010-123-9876', 

...           'age' : 30}


>>> >>> dict_1['name']

'Python Friend'

>>> dict_1['name'] = 'R Friend' # (1) updating an existing entry

>>> dict_1['name']

'R Friend'

>>> 

>>> dict_1['gender'] = 'Male' # (2) Adding a new entry

>>> dict_1

{'name': 'R Friend', 'region': 'Busan, Korea', 'phone': '010-123-9876', 'age': 30, 'gender': 'Male'}

 




 4. 사전의 {키:값} 요소 삭제, 값 삭제, 사전 전체 삭제하기 (Deleting Dictionary Elements)

   : del statement, clear() method


(4-1) 사전 자료형의 'Key'를 사용하여 특정 {Key : Value} 요소(entry) 제거 : del dict[Key]

(4-2) 사전 자료형의 모든 'Value' 제거 : dict.clear()

(4-3) 사전 자료형을 통째로 삭제 : del dict



# (4-1) Removing entry with key 'name' : del dict[Key}

>>> dict_1 = {'name' : 'Python Friend', 

...           'region' : 'Busan, Korea', 

...           'phone' : '010-123-9876', 

...           'age' : 30}

>>> dict_1

{'name': 'Python Friend', 'region': 'Busan, Korea', 'phone': '010-123-9876', 'age': 30}

>>> dict_1['name']

'Python Friend'

>>> del dict_1['name'] # remove entry with key 'name'

>>> dict_1['name']

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

KeyError: 'name'



# (4-2) Removing all entries in dict using dict.clear() method

>>> dict_1 = {'name' : 'Python Friend', 

...           'region' : 'Busan, Korea', 

...           'phone' : '010-123-9876', 

...           'age' : 30}

>>> dict_1

{'name': 'Python Friend', 'region': 'Busan, Korea', 'phone': '010-123-9876', 'age': 30}

>>> dict_1.clear()

>>> dict_1

{}



# (4-3) Deleting entire dictionary using del statement

>>> dict_1 = {'name' : 'Python Friend', 

...           'region' : 'Busan, Korea', 

...           'phone' : '010-123-9876', 

...           'age' : 30}

>>> dict_1

{'name': 'Python Friend', 'region': 'Busan, Korea', 'phone': '010-123-9876', 'age': 30}

>>> del dict_1

>>> dict_1

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'dict_1' is not defined

 




  • 사전 자료형 키의 2가지 특징 (2 Properties of Dictionary Key)


 5. 사전의 키 당 1개의 값 할당, 만약 사전의 키 중복 시 마지막 키의 값으로 할당 

     (In case of duplicate key in Dictionary, the last Value is assigned to the Key)



# More than one entry per key not allowed

# If keys are duplicated, then the last Value of Key will be assigned

>>> dict_1 = {'name' : 'Python Friend'

...           'region' : 'Busan, Korea', 

...           'phone' : '010-123-9876', 

...           'age' : 30,

...           'name' : 'R Friend'}

>>> dict_1

{'name': 'R Friend', 'region': 'Busan, Korea', 'phone': '010-123-9876', 'age': 30}

>>> dict_1['name']

'R Friend'

 




 6. 사전의 키는 변경 불가 (Dictionary Keys must be immutable)

    : Strings, Numbers, Tuples 은 Key로 가능, Lists 는 Key로 불가


사전의 키는 변경 불가능해야 합니다. 따라서 문자열(Strings), 숫자(Numbers), 튜플(Tuples) 가 사전의 키(Dictionary Key)로 활용 가능하며, 리스트(List)는 사전의 키로 사용 불가능합니다.  만약 리스트( [obj1, obj2, ... ] )를 사전의 키로 사용하려고 입력하면 TypeError: unhashable type: 'list' 라는 에러 메시지가 발생합니다. 



# TypeError: unhashable type 'list'

>>> dict_1 = {['name'] : 'Python Friend', 

...           'region' : 'Busan, Korea', 

...           'phone' : '010-123-9876', 

...           'age' : 30}

Traceback (most recent call last):

  File "<stdin>", line 4, in <module>

TypeError: unhashable type: 'list'

 



다음번 포스팅에서는 파이썬 사전 자료형의 내장 함수와 메소드 (Python Dictionary built-in functions, methods)에 대해서 알아보겠습니다. 


많은 도움이 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^



728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 파이썬 자료형 중에서 튜플의 생성, 삭제, 인덱싱, 슬라이싱 및 기본 연산자들에 대해서 알아보았습니다. 


이번 포스팅에서는 파이썬 튜플의 내장 함수(Tuple Built-in Functions)와 메소드(Tuple Methods)에 대해서 알아보겠습니다. 


참고로, 튜플 내장함수는 리스트와 동일하며, 메소드는 리스트 대비 매우 적습니다. 왜냐하면 튜플(Tuple)은 개별 요소 변경이 불가능(Immutable) 하기 때문에 요소 추가, 튜플 확장, 요소 제거, 뒤집기, 정렬 등이 안되기 때문입니다. 


이번 포스팅은 매우 쉽기도 하려니와, 아주 짧게 간단하게 끝나겠네요. ^^



[ 파이썬 튜플의 내장 함수 및 메소드 (Python Tuple built-in functions and methods) ]





1. 파이썬 튜플의 내장 함수 (Python Tuple built-in functions)


 1-1. len(tuple) : 튜플의 전체 길이 (length)



# en() : Gives the total length of the tuple

>>> len((1, 2, 3))

3

 




 1-2. max(tuple) : 튜플 안에 있는 요소값 중 최대값 반환 (문자는 알파벳 기준)



# max(): Returns item from the tuple with max value

>>> len((1, 2, 3))

3

>>> max((1, 2, 3, 4, 5))

5

>>> max(('a', 'b', 'c', 'd', 'e')) # As for character, in order of alphabet

'e'

 



튜플 안의 요소값들이 문자열과 숫자가 섞여 있을 경우 max() 메소드를 적용하면 TypeError 가 발생합니다. 



# TypeError for max() method when 'str' and 'int' are mixed in a tuple

>>> max((1, 2, 3, 'a', 'b', 'c'))

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: '>' not supported between instances of 'str' and 'int'

 




 1-3. min(tuple) : 튜플 안에 있는 요소값 중 최소값 반환 (문자는 알파벳 기준)


 

# min() : Returns item from the tuple with min value

>>> min((1, 2, 3, 4, 5))

1

>>> min(('a', 'b', 'c', 'd', 'e'))

'a'





 1-4. tuple(seq) : 리스트를 튜플로 변환 (converting a list into tuple)



# tuple(seq) : Converts a list to tuple

>>> my_list = [1, 2, 'a', 'b']

>>> type(my_list)

<class 'list'>

>>> 

>>> my_tup = tuple(my_list)

my_tup

>>> (1, 2, 'a', 'b')

>>> type(my_tup)

<class 'tuple'>

 





2. 파이썬 튜플의 메소드 (Python Tuple methods)


 2-1. tuple.count() : 튜플 내 요소의 개수 세기


 

# tuple.count(obj.) : Returns the total number of obj. in tuple

>>> tup = (1, 2, 3, 4, 5, 2, 2)

>>> tup.count(2)

3





 2-2. tuple.index(obj.) : 튜플 내 요소가 있는 위치 index 반환


만약 똑같은 값이 2개 이상 들어있는 경우 처음 요소 값이 나타나는 위치의 index 를 반환합니다. 



# tuple.index(obj.) : Returns the index of a obj. in tuple

>>> tup = (1, 2, 3, 4, 5, 2, 2)

>>> tup.index(2)

1

 



다음번 포스팅에서는 사전(Dictionary) 자료형의 기본 활용 및 특징에 대해서 알아보겠습니다. 


많은 도움이 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^



728x90
반응형
Posted by Rfriend
,

파이썬에는 다수의 데이터를 다룰 수 있는 자료형으로 '리스트(List)', '튜플(Tuple)', '사전(Dictionary)' 자료형이 있습니다. 


지난번 포스팅에서는 '리스트(List)' 자료형에 대해서 알아보았으며, 이번 포스팅에서는 2회에 나누어서 '튜플(Tuple)' 자료형에 대해서 소개하겠습니다.  


튜플(Tuple) 자료형은 리스트(List) 와 유사하면서도 큰 차이가 있어서 처음 파이썬 사용하는 분이라면 혼동스러울 수 있습니다. 


튜플과 리스트는 다른 형태의 다수의 자료, 객체를 하나의 순서열(sequence)로 묶어서 자료를 관리할 수 있다는 공통점이 있습니다만, 튜플(Tuple)은 자료 변경이 불가능(A tuple is a sequence of immutable Python objects) 하다는 점이, 변경이 가능한 리스트와는 다른 결정적인 차이점입니다. (참고: 문자열(String)도 튜플처럼 변경이 불가능한 자료형임) 


리스트는 꺽인 대괄호([ ], square brackets)로 양 옆을 싸서 생성하는 반면에, 튜플은 둥근 괄호( ( ), parentheses, round brackets)를 사용해서 만듭니다. 



[ 파이썬의 5가지 자료형 (Python's 5 Data Types) ]




변경이 불가능한 자료형(Immutable Type)이 왜 필요할까 싶을텐데요, '소프트웨어 성능 향상'과 '프로그래머가 자기 코드를 신뢰할 수 있다'는 장점이 있습니다. 


 

[ 변경이 불가능한 자료형이 왜 필요할까? ]


 "변경이 불가능한 자료형은 변경 가능한 자료형에 비해 소프트웨어의 성능을 향상하는데 도움을 줍니다. 변경 가능한 자료형과는 달리 데이터를 할당할 공간의 내용이나 크기가 달라지지 않기 때문에 생성 과정이 간단하고, 데이터가 오염되지 않을 것이라는 보장이 있기 때문에 복사본을 만드는 대신 그냥 원본을 사용해도 되기 때문입니다. 


 사실 이런 성능보다도, 프로그래머가 자기 코드를 신뢰할 수 있다는 것이 변경이 불가능한 자료형의 가장 큰 장점입니다. 프로그래머가 수천~수만 줄의 코드를 작성하다보면 변경되지 않아야 할 데이터를 오염시키는 버그를 만들 가능성이 높습니다. 이런 실수를 몇 군데 해놓으면 어디에서 문제가 생겼는지를 찾아내기가 상당히 어렵습니다. 그래서 코드를 설계할 때부터 변경이 가능한 데이터와 그렇지 않은 데이터를 정리해서 코드에 반영하는 것이 필요합니다."


* 출처 : '뇌를 자극하는 파이썬 3', 박상현 지음, 한빛미디어





자, 이제 둥근 괄호( ( ), parentheses)나 혹은 콤마( ',' , comma)를 사용해서 튜플을 만들어볼까요? 


 1. 괄호와 콤마를 사용해서 튜플 만들기 (Creating tuple using parentheses or comma) : (obj, )


(1-1). 둥근 괄호 ('( )', parentheses, round brackets)를 사용해서 튜플 만들기



# tuples are encolsed within parentheses

>>> tuple_1 = ('abc', 123, 3.14, ['edf', 456], ('gh', 'st'))

>>> tuple_1

('abc', 123, 3.14, ['edf', 456], ('gh', 'st'))

>>> type(tuple_1)

<class 'tuple'>




(1-2) 괄호 없이 콤마를 사용해서 튜플 만들기 (Tuple packing)



# tuple is created by putting different comma-separated values (without parentheses)

>>> tuple_1_2 = 'abc', 123, 3.14, ['edf', 456], ('gh', 'st')

>>> tuple_1_2

('abc', 123, 3.14, ['edf', 456], ('gh', 'st'))

>>> type(tuple_1_2)

<class 'tuple'>

 



(1-3) 요소가 하나뿐인 튜플 만들기 => 콤마 포함 필요



# creating tuple with 1 element using parentheses and a comma

>>> tuple_1_element_with_comma = (123, )

>>> tuple_1_element_with_comma

(123,)

>>> type(tuple_1_element_with_comma)

<class 'tuple'>

 



요소가 하나뿐이 객체를 괄호로 싸기만 하고 뒤에 콤마를 포함하지 않는 경우, 튜플이 아니라 정수형(int.) 자료형으로 저장이 되므로 주의가 필요합니다. 



# if you don't include a comma for a single value, it will be a int., not a tuple

>>> int_1_element_without_comma = (123) # without a comma

>>> int_1_element_without_comma

123

>>> type(int_1_element_without_comma)

<class 'int'>

 




  2. 튜플 삭제(Deleting a Tuple): del tuple


튜플은 변경이 불가능하기 때문에 개별 요소(individual elements)를 제거하는 것은 불가능합니다 (리스트는 pop 메소드나 remove 메소드로 개별 요소 삭제 가능).  대신에 튜플을 통째로 삭제(entire tuple)하는 것은 del 선언문을 사용해서 가능합니다. 


 

# Deleting an entire Tuple with 'del' statement

>>> tuple_1 = ('abc', 123, 3.14, ['edf', 456], ('gh', 'st'))

>>> tuple_1

('abc', 123, 3.14, ['edf', 456], ('gh', 'st'))

>>> del tuple_1

>>> tuple_1 # tuple_1 is removed with del statement above

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'tuple_1' is not defined





  3. 튜플 개별 요소를 변경하려면 TypeError 발생



>>> tup_1 = (1, 2, 3)

>>> tup_1[0] = 4

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

 




 4. 튜플 인덱싱, 슬라이싱 (Tuple indexing, slicing) : tup[0], tup[0:3], tup[-1], tup[-3:-1]


튜플도 리스트나 문자열과 같이 순서열 자료형(sequences) 이기 때문에 대괄호([ ], square brackets)를 사용해서 특정 요소를 인덱싱(indexing)하거나 구간 범위의 요소들을 슬라이싱(slicing) 하는 것이 가능합니다.  인덱싱은 '0'부터 시작합니다. 

tup[0]은 정수를, tup[0:1]은 튜플을 반환함을 주의하세요. 





# Tuple indexing and slicing start at zero

>>> tuple_2 = (1, 2, 3, 4, 5, 6, 7)

>>> tuple_2

(1, 2, 3, 4, 5, 6, 7)

>>> tuple_2[0] # Indexing one element of tuple => int.

1

>>> tuple_2[0:1] # Indexing one element of tuple => tutple

(1,)

>>> tuple_2[0:3] # Tuple slicing

(1, 2, 3)

>>> tuple_2[3:] # Tuple slicing

(4, 5, 6, 7)

 



튜플 인덱싱이나 슬라이싱을 할 때 '-' (negative) 부호가 붙으면 오른쪽에서 부터 시작하며, 이때 제일 오른쪽이 '-1'입니다. 



# In case of negative(-), it counts from the rigth

>>> tuple_2 = (1, 2, 3, 4, 5, 6, 7)

>>> tuple_2

(1, 2, 3, 4, 5, 6, 7)

>>> tuple_2[-1] # indexing from the right

7

>>> tuple_2[-1:]

(7,)

>>> tuple_2[-3:-1] # slicing from the right

(5, 6)

>>> tuple_2[-3:]

(5, 6, 7)





 5. 여러 개 데이터를 튜플로 묶기(Tuple Packing)

          <--> 튜플의 각 요소를 여러 개 변수에 할당하기(Tuple Unpacking)



# Tuple packing

>>> tup_packing = 'Mr.Lee', 25, 'Seoul', 'KOREA'

>>> tup_packing

('Mr.Lee', 25, 'Seoul', 'KOREA')


# Tuple unpacking

>>> name, age, city, nationality = tup_packing

>>> name

'Mr.Lee'

>>> age

25

>>> city

'Seoul'

>>> nationality

'KOREA'

 



튜플의 각 요소를 여러 개의 변수에 할당(Tuple unpacking)할 때 튜플 내 요소의 개수와 할당하려는 변수의 개수가 서로 같지 않다면 ValueError 가 발생합니다. 



# if the number of unpack vaule and variable is not the same, then ValueError occurs

>>> tup_packing # 4 elements

('Mr.Lee', 25, 'Seoul', 'KOREA')

>>> name, age, city = tup_packing # 3 variables

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: too many values to unpack (expected 3)

 




 6. 튜플의 기본 연산자 (Basic Tuples Operations)


튜플의 기본 연산자에는 (리스트와 동일하게) 길이를 세는 len() 함수, 튜플을 합치는 '+' 연산자, 튜플 내 요소값을 반복하는 '*' 연산자, 튜플 내 요소값이 존재하는지 여부를 블리언값으로 반환하는 'in' 연산자, 그리고 for loop 반복 연산자가 있습니다. 


설명 (Description)

파이썬 코드 (Python Code) 

결과 (Results) 

 튜플 길이 (Length)

 len((1, 2, 3))

 3

 튜플 합치기 (Concatenation)

 (1, 2, 3) + ('a', 'b', 'c')

 (1, 2, 3, 'a', 'b', 'c')

 반복 (Repetition)

 (1, 'a')*3

 (1, 'a', 1, 'a', 1, 'a')

 소속 여부 (Membership)

 3 in (1, 2, 3)

 4 in (1, 2, 3)

 True

 False

 for loop 반복 (iteration)

 for x in (1, 2, 3):

    print(x)

 1

 2

 3



다음번 포스팅에서는 튜플의 내장 함수(Tuple built-in functions)와 튜플 메소드(Tuple methods)에 대해서 알아보겠습니다. 


많은 도움이 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^



728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 파이썬의 자료형 중에서 리스트(Python List)의 생성 및 기본 사용법에 대해서 알아보았습니다.  


이번 포스팅에서는 이어서 파이썬 리스트의 내장 함수와 메소드(Python List built-in functions and methods)에 대해서 소개하겠습니다. 


리스트 자료형이 다른 유형의 자료를 한번에 다룰 수 있기 때문에 리스트를 잘 사용하면 코드를 한결 깔끔하게 짤 수 있습니다.  그리고 리스트 내의 요소(element)를 갱신할 수 있기 때문에 데이터 분석할 때 리스트가 애용된다고도 했는데요, 이번 포스팅에서 소개하는 리스트 내장 함수(list built-in functions)와 다양한 기능을 제공하는 메소드(list methods)도 리스트 자료형이 자주 사용되고 또 중요한 자료형인 이유 중의 하나입니다. 






1. 파이썬 리스트 내장 함수 (Python List built-in functions)


 1-1. len(list) : 리스트의 전체 길이


for loop 문에서 자주 사용하곤 합니다. 



# (1-1) len(list) : Gives the total length of the list

>>> list1 = [1, 2, 3]

>>> list2 = ['a', 'b', 'c', 'd']

>>> len(list1)

3

>>> len(list2)

4

 




  1-2. max(list) : 리스트 안에 있는 요소 중에서 최대값 반환 (문자인 경우 알파벳 순서 기준)



# (1-2) max(list) : Returns item from the list with max value

>>> list1 = [1, 2, 3]

>>> max(list1)

3

>>> 

>>> list2 = ['a', 'b', 'c', 'd']

>>> max(list2)

'd'

 




  1-3. min(list) : 리스트 안에 있는 요소 중에서 최소값 반환 (문자인 경우 알파벳 순서 기준)



# (1-3) min(list) : Returns item from the list with min value

>>> list1 = [1, 2, 3]

>>> min(list1)

1

>>> 

>>> list2 = ['a', 'b', 'c', 'd']

>>> min(list2)

'a'

 




  1-4. list(seq) : 튜플을 리스트 자료형으로 변환



# (1-4) list(seq) : Converts a tuple into list

>>> tup = ('aaa', 'bbb', 'ccc') # tuple

>>> tup

('aaa', 'bbb', 'ccc')

>>> 

>>> list_tup = list(tup) # converting a tuple into list

>>> list_tup

['aaa', 'bbb', 'ccc']

>>> type(list_tup)

<class 'list'>

 




 1-5. cmp(list1, list2) : 리스크 안의 요소 비교하여 불리언값 반환 (단, Python 3.x 버전에서는 삭제됨)



Python 2.x 버전에서는 두 개의 리스트 원소를 비교해서 불리언값을 반환하는 cmp(list1, list2) 라는 내장 함수가 있었습니다만, Python 3.x 버전에서는 삭제되었습니다.  이전 cmp(list1, list2) 내장 함수의 기능은 아래의 '==' 연산자를 사용하면 Python 3.x 버전에서 동일한 결과를 얻을 수 있습니다. 



# cmp() has been removed in py3.x.

>>> list1 = [1, 2, 3]

>>> list2 = ['a', 'b', 'c', 'd']

>>> list3 = [1, 2, 3]

>>> 

>>> list1 == list2

False

>>> list1 == list3 

True

 






2. 파이썬 리스트 메소드 (Python List methods)


  2-1. list.append(obj) : 기존 리스트에 1개의 요소를 이어 붙이기



# (2-1) list.append(obj) : Appends object obj to list

>>> list1 = [1, 2, 'a', 'b']

>>> list1.append('c') # append an element

>>> list1

[1, 2, 'a', 'b', 'c']

 



append() 메소드를 사용할 때는 괄호 안에 추가하려는 요소를 1개만 써야 하며, 2개 이상 쓰면 TypeError 가 발생합니다. 



>>> list1.append('c', 'd') # TypeError

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: append() takes exactly one argument (2 given)

 




  2-2. list.extend(seq) : 기존 리스트에 다른 리스트를 이어 붙이기



# (2-2) list.extend(seq) : Appends the contents of seq to list

>>> list2 = [1, 2, 'a', 'b', 'c']

>>> list3 = [3, 3, 4, 'd', 'd']

>>> 

>>> list3.extend(list2)

>>> list3

[3, 3, 4, 'd', 'd', 1, 2, 'a', 'b', 'c']

 




  2-3. list.count(obj) : 리스트 안에 obj 가 몇 개 들어있는지 세어서 개수를 반환



# (2-3) list.count(obj) : Returns count of how many times obj occurs in list

>>> list3 = [3, 3, 4, 'd', 'd', 'd', 'e']

>>> list3.count(3)

2

>>> list3.count('d')

3

 




  2-4. list.index(obj) : 리스트에서 obj 요소 값이 있는 가장 작은 index 값 반환



# (2-4) list.index(obj) : Returns the lowest index in list that obj appears

>>> list4 = [1, 2, 'a', 'b', 'c', 'a']

>>> 

>>> list4.index('a')    

2

>>> list4.index('c')   

4

 



만약 리스트 안에 없는 값을 obj 에 넣어서 list.index(obj) 를 실행하면 ValueError 가 발생합니다. 



# ValueError: 'ggg' is not in list

>>> list4.index('ggg') # ValueError

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: 'ggg' is not in list

 




 2-5. list.insert(index, obj) : 기존 리스트의 index 위치에 obj 값을 삽입



# (2-5) list.insert(index, obj) : Inserts obj into list at offset index

>>> list5 = [1, 2, 'a', 'b', 'c']

>>> list5

[1, 2, 'a', 'b', 'c']

>>> 

>>> list5.insert(3, 'kkkk')

>>> list5

[1, 2, 'a', 'kkkk', 'b', 'c']

 




  2-6. list.pop(obj=list[-1]) : 기존 리스트에서 마지막 요소를 제거하고, 제거된 마지막 요소를 반환



# (2-6) list.pop(obj=list[-1]) : Removes and returns last object or obj from the list

>>> list6 = [1, 2, 'a', 'b', 'c']

>>> list6.pop() # removes the last element

'c'

>>> list6

[1, 2, 'a', 'b']

 



pop() 의 괄호 안에 정수(integer)를 넣어주면, 기존 리스트에서 해당 정수 위치의 index 값을 제거하고, 제거된 index 위치 요소의 값을 반환합니다. 



>>> list6 = [1, 2, 'a', 'b', 'c']

>>> list6.pop(2) # removes the element of the index

'a'

>>> list6

[1, 2, 'b', 'c']

 




 2-7. list.remove(obj) : 기존 리스트에서 remove(obj) 메소드 안의 obj 객체를 제거



# (2-7) list.remove(obj) : Removes the given object from the list

>>> list7 = [1, 2, 'a', 'b', 'c']

>>> list7.remove(1)

>>> list7

[2, 'a', 'b', 'c']

>>> 

>>> list7.remove('a')

>>> list7

[2, 'b', 'c']




remove() 메소드는 괄호 안에 단 1개의 argument 만을 사용하며, 2개 이상을 넣으면 TypeError 가 발생합니다. 



# TypeError: remove() takes exactly one argument

>>> list7 = [1, 2, 'a', 'b', 'c']

>>> list7.remove(1, 'a') # TypeError

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: remove() takes exactly one argument (2 given)

 




 2-8. list.reverse() : 리스트의 객체를 리스트 안에서 순서를 반대로 뒤집기



# (2-8) list.reverse() : Reverses objects of list in place

>>> list8 = [1, 2, 'a', 'b', 'c']

>>> list8.reverse()

>>> 

>>> list8

['c', 'b', 'a', 2, 1]

 




  2-9. list.sort() : 리스트의 객체를 리스트 안에서 순서대로 정렬하기 (디폴트 오름차순)


sort() 메소드의 디폴트오름차순(ascending) 입니다. 



>>> list9 = [3, 1, 9, 4, 2, 8]

>>> list9.sort() # ascending order, default setting

>>> list9

[1, 2, 3, 4, 8, 9]

 



내림차순(descending)으로 정렬하고 싶다면 list.sort(reverse=True) 처럼 옵션을 설정해주면 됩니다. 



>>> list9 = [3, 1, 9, 4, 2, 8]

>>> list9.sort(reverse=True) # descending order

>>> list9

[9, 8, 4, 3, 2, 1]

 



문자는 알파벳 순서로 정렬합니다. 


# sorting character by alphabetical order

>>> list9_2 = ['c', 'a', 'b']

>>> list9_2.sort()

>>> list9_2

['a', 'b', 'c']

 



숫자와 문자가 섞여있는 리스트에 sort() 메소드를 적용하면 TypeError 가 발생합니다. 


# TypeError when applying sort() method for list with number and character

>>> list9_3 = [3, 1, 9, 'c', 'a', 'b']

>>> list9_3.sort()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: '<' not supported between instances of 'str' and 'int'

 



많은 도움이 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^


다음번 포스팅에서는 파이썬 자료형 중에서 튜플(Tuple)의 기본 사용법에 대해서 알아보겠습니다. 





728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 파이썬에서 단일 데이터를 다루는 자료형인 숫자와 문자열에 대해서 알아보았습니다. 


파이썬에는 다수의 데이터를 다룰 수 있는 자료형으로 리스트(List), 튜플(Tuple), 사전(Dictionary) 자료형이 있습니다.  

이번 포스팅에서는 이중에서 리스트(List) 자료형에 대해서 알아보겠습니다. 


리스트(List) 자료형은 다수 데이터가 서로 다른 형태의 자료여도 되며, 변경 가능하다는 점 때문에 데이터 분석에서 정말 많이 사용되는 만큼, 정말 중요한 자료형입니다.  (↔ 튜플은 자료 갱신이 안됨)


리스트(List)는 대괄호(square brackets, [ ]) 을 사용해서 자료값을 감싸주고, 대괄호 안의 다수의 값들은 콤마(comma)로 구분을 해줍니다. 



[ 파이썬의 5가지 자료형 (Python's 5 Data Types) ]





먼저 리스트 생성, 삭제, 인덱싱 및 슬라이싱, 기본 연산자를 소개하고, 리스트를 다루는 내장 함수와 메소드는 다음번에 나누어서 설명하겠습니다. 



 1. 대괄호와 콤마로 리스트 생성 (creating a list with square brackets and comma separation)


리스트 안에 문자열, 정수, 부동소수형, 리스트, 튜플 등 다양한 형태의 자료들이 들어갈 수 있으며, 콤마로 구분해주고, 대괄호로 감싸줍니다.  



# List : contains items separated by commas and enclosed within square brackets([])

>>> list_1 = ['abc', 123, 3.14, ['edf', 456], ('gh', 'st')]

>>> list_1

['abc', 123, 3.14, ['edf', 456], ('gh', 'st')]

 




  2. 리스트 삭제 (Deleting a list) : del



>>> list_1 = ['abc', 123, 3.14, ['edf', 456], ('gh', 'st')]

>>> list_1

['abc', 123, 3.14, ['edf', 456], ('gh', 'st')]

>>> 

>>> del list_1

>>> list_1

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'list_1' is not defined

 




  3. 리스트 안의 특정 위치의 값을 새로운 값으로 갱신 (Updating a list) : list[index] = value



>>> list_1

['abc', 123, 3.14, ['edf', 456], ('gh', 'st')]

>>> list_1[1]

123

>>> list_1[1] = 111

>>> list_1

['abc', 111, 3.14, ['edf', 456], ('gh', 'st')]

 




  4. 리스트 인덱싱, 슬라이싱 (Indexing, Slicing a list)


리스트도 순서열(sequences)이므로, 문자열에서 사용했던 방법과 동일하게 인덱싱, 슬라이싱(indexing, slicing)이 가능합니다. 첫번째 자리는 '0'부터 인덱싱이 시작합니다. (R은 '1'부터 시작하므로 혼동하지 않도록 주의 요함)



# the slice operator : [:] with indexes starting at 0 in the beginning of the list

>>> list_1 = ['abc', 123, 3.14, ['edf', 456], ('gh', 'st')]

>>> list_1

['abc', 123, 3.14, ['edf', 456], ('gh', 'st')]

>>> 

>>> list_1[0]

'abc'

>>> list_1[0:3]

['abc', 123, 3.14]

>>> list_1[3:]

[['edf', 456], ('gh', 'st')]

 



마이너스 부호('-')를 붙여주면 뒤에서부터 인덱싱(indexing)이 시작합니다. 



>>> list_1 = ['abc', 123, 3.14, ['edf', 456], ('gh', 'st')]

>>> list_1

['abc', 123, 3.14, ['edf', 456], ('gh', 'st')]

>>> 

>>> list_1[-1] # indexing starting from the last using '-1' : minus (-) sign

('gh', 'st')

>>> list_1[-3:-1]

[3.14, ['edf', 456]]

 




  5. 리스트 기본 연산자 (Basic List Operations)


리스트의 기본 연산자(basic list operations)에는 리스트 길이는 재는 len() 함수, 리스트를 합치는 + 연산자, 리스트 값을 반복하는 * 연산자, 소속 여부 블리언값(True, False)을 반환하는 in 연산자, 함수를 반복하는데 사용하는 for loop 문 등이 있습니다. 


[ 리스트 기본 연산자 (basic list operations) ]


설명 (description)

파이썬 표현 (python expression)

결과 (results)

 리스트 길이 (length)

 len([1, 2, 3])

 3

 리스트 합치기 (concatenation)

 [1, 2, 3] + [4, 5, 6]

 [1, 2, 3, 4, 5, 6]

 반복 (repetition)

 [1, 2, 3]*3

 [1, 2, 3, 1, 2, 3, 1, 2, 3]

 소속 여부 (membership)

 1 in [1, 2, 3]

4 in [1, 2, 3]

 True

 False

 for loop 반복 (iteration)

 for x in [1, 2, 3]: print (x);

 1 

 2 

 3 




다음번 포스팅에서는 리스트 내장 함수 및 메소드(Python List built-in functions and methods)에 대해서 알아보겠습니다. 


많은 도움이 되었기를 바랍니다. 


이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^



728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 파이썬 자료형식 중 '문자열(string)'에 특화된 내장 함수들인 다양한 문자열 메소드 (built-in string methods) 들에 대해서 알아보았습니다. 


이번 포스팅에서는 문자열에 특화된 연산자, 메소드로서 


- 형식을 갖춘 문자열을 만들어주는 연산자: %

- 형식을 갖춘 문자열을 만들어주는 메소드: format() 


에 대해서 알아보겠습니다. 


텐서플로우로 딥러닝 공부하다보면 제일 마지막 부근에 아래와 같은 모델 훈련 진행 경과를 확인하는 코드가 들어있습니다. 이번 포스팅이 보고 나면 아래의 코드가 무엇을 의미하는지 눈에 읽히기 시작할 것입니다. ^^



# 신경망 모델 학습 진행 경과 확인 python code


print('Epoch:', '%04d' % (epoch + 1),

         'Avg. cost =', '{:.3f}'.format(total_cost / total_batch))

 



처음에 문자열 형식(format)을 설정해주는 % 연산자와 format() 문자열 메소드를 봤었을 땐 생소하고, 해석이 안되서 좀 당황했었습니다. 그런데 파이썬 매뉴얼 보고 나서 의미를 파악하고 난 후, 그리고 요즘 텐서플로우로 딥러닝 공부하면서 코드를 자꾸 보다보니 이젠 익숙해지기도 하고, 많이 유용하다는 생각도 듭니다. 



[ Python String Formatting Operator % and Method format() ]




간단한 예를 들어서 설명해보겠습니다. 


 (1) Format 을 갖춘 문자열을 만들어주는 연산자 (String Formatting Operator): %



>>> "I am %s and %d years old" %('Mr.Hong', 40)

'I am Mr.Hong and 40 years old'

 



'%'의 뒤에 함께 사용할 수 있는, 문자열 형식을 지정해주는 symbol 들에는 아래와 같은 것들이 있습니다. 많이 사용할 만한 format symbol은 파란색으로 강조를 했습니다.


%와 함께 사용하는 형식 기호

(Format Symbol with %) 

변환 (Conversion)

 %c

 문자 (character)

 %s

 str() 메소드를 사용해서 문자열로 변환한 후 formatting

%i 

 부호가 있는 십진법 정수 (signed decimal integer)

 %d

 부호가 있는 십진법 정수 (signed decimal integer)

 %u

 부호가 없는 십진법 정수 (unsigned decimal integer)

 %o

 8진법 정수 (octal integer)

 %x

 소문자의 16진법 정수 (hexadecimal integer, lowercase letters)

 %X

 대문자의 16진법 정수 (hexadecimal integer, UPPERcase letters)

 %e

 소자 'e'를 사용한 지수 표기 (exponential notation with lowercase 'e')

 %E

 대문자 'E'를 사용한 지수 표기 (exponential notation with UPPERcase 'E')

 %f

 부동소수형 실수 (floating point real number)

 %g

 %f(부동소수형 실수)와 %e (소문자 'e' 지수 표기) 의 단축형 표기

 %G

 %f(부동소수형 실수)와 %E(대문자 'E' 지수 표기)의 단축형 표기




위의 Format Symbol을 사용하면 원하는 Format의 데이터가 아닐 경우 'TypeError' (예: TypeError: %d format: a number is required, not str) 가 납니다. 



>>> "I am %s and %d years old" %('Mr.Hong', '40')  # '40' is not a number, but a string

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: %d format: a number is required, not str

 




부호가 있는 십진법 정수를 나타내는 문자열 포맷 연산자인 %d 의 경우 아래의 "%04d" % (5) 처럼 '%'와 'd' 사이에 '0'과 '숫자'를 써주게 되면 => % ( ) 안의 십진수 정수가 만약 입력한 '숫자'(예에서는 '4') 만큼의 총 자리수보다 작다면 그 모자라는 만큼을 '0'으로 채워줍니다. 말로 설명하기가 쉽지 않은데요(^^;), 아래의 예시를 보면 이해가 쉬울 것 같습니다. 



>>> "%04d" % (5)

'0005'

>>> "%04d" % (55)

'0055'

>>> "%04d" % (555)

'0555'

>>> "%04d" % (5555)

'5555'

>>> "%04d" % (55555)

'55555'

 




부동소수형 실수를 나타내는 문자열 포맷 연산자인 %f 의 경우 아래의 "%.3f" % (0.5) 처럼 '%'와 'f' 사이에 점 '.'과 '숫자'를 써주게 되면 => % ( ) 안의 부동소수형 실수가 만약 입력한 '숫자' (예에서는 '3') 만큼의 총 소수점 자리수보다 작다면 뒷부분의 모자라는 만큼을 '0'으로 채워줍니다.  역시, 글로 설명을 들으면 어려운데요(^^;), 아래 예를 살펴보시기 바랍니다. 



>>> "%.3f" % (5)

'5.000'

>>> "%.3f" % (0.5)

'0.500'

>>> "%.3f" % (0.55)

'0.550'

>>> "%.3f" % (0.555)

'0.555'

>>> "%.3f" % (0.5555)

'0.555'

 




처음 시작할 때 예로 들었던 딥러닝 텐서플로우 코드의 말미에 있다는 파이썬 코드가 이제 눈어 들어올 것입니다. epoch 와 total_cost, total_batch 변수에 임의의 숫자를 넣어서 아래에 print 를 해보았습니다. 



>>> print('Epoch:', '%04d' % (100),

...       'Avg. cost =', '{:.3f}'.format(10 / 1000))

Epoch: 0100 Avg. cost = 0.010

 




formatting operator % 를 사용한 lambda 함수 map() 함수를 같이 사용하여 pandas DataFrame의 숫자형 변수의 소수점 자리수(decimal point format)를 지정, 변경할 수 있습니다. 


In [1]: import pandas as pd


In [2]: df = pd.DataFrame({'id': ['a', 'b', 'c', 'd'],

   ...: 'val': [1.045, 5.200, 0.051, 8.912]})


In [3]: df

Out[3]:

  id    val

0  a  1.045

1  b  5.200

2  c  0.051

3  d  8.912


In [4]: formater = lambda x:" %.2f" %(x)


In [5]: df['val'] = df['val'].map(formater)


In [6]: df

Out[6]:

  id    val

0  a   1.04

1  b   5.20

2  c   0.05

3  d   8.91


* map() 대신에 apply() 를 사용해도 결과는 동일합니다. 

* map(), apply()로 해서 소수점 2자리수로 변경을 하면 float8 이 string 으로 데이터 유형이 변경됩니다. 




 (2) Format 을 갖춘 문자열을 만들어주는 메소드 (String Formatting Method): format()


format() 메소드를 사용해서 형식을 갖춘 문자열을 만드는 방법에는 두 가지가 있습니다. 


(2-1) 먼저 대괄호 { } 안에 변수 이름(variable name)을 지정해주고, format(variable name = value) 처럼 값을 지정해주는 방법입니다.  대괄호 { } 안에 문자열 형식을 지정할 변수가 많다면 명시적으로 변수명을 설정해주기 때문에 헷갈리지도 않고 코드 가독성도 높여주는 방법입니다. 



>>> "I am {name} and {age} years old".format(name='Mr.Hong', age=40)

'I am Mr.Hong and 40 years old'




format() 메소드 안에 값을 입력해줄 때 변수명별로 대입해서 입력하기 때문에 순서와는 상관이 없습니다. 



>>> "I am {name} and {age} years old".format(age=40name='Mr.Hong')

'I am Mr.Hong and 40 years old'

 




(2-2) 두번째 방법은 대괄호 { } 안에 문자열 입력하는 순서대로 데이터를 넣어주면 지정한 포맷대로 문자열을 만들어주는 방법입니다. 



>>> "I am {0} and {1} years old".format('Mr.Hong', 40)

'I am Mr.Hong and 40 years old'

 



format() 메소드 안에 값을 입력하는 순서가 바뀌면 출력되는 문자열에 입력하는 값이 의도했던 바와는 다르게 실수로 뒤엉커버릴 수 있습니다. 따라서 대괄호 { }로 포맷을 설정할 변수가 많은 경우에는 실수를 유발할 위험이 있는 방법이니, 첫번째처럼 명시적으로 변수명을 지정해주는게 좋겠습니다. 



>>> "I am {0} and {1} years old".format(40, 'Mr.Hong') # sequence matters

'I am 40 and Mr.Hong years old'

 

 


다음번 포스팅에서는 파이썬 리스트 (List)자료형의 생성 및 기본 활용법에 대해서 알아보겠습니다. 


많은 도움이 되었기를 바랍니다. 


이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^



728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 파이썬의 자료 유형인 

 - 숫자(Number), 

 - 문자열(String), 

 - 리스트(List), 

 - 튜플(Tuple), 

 - 사전(Dictionary) 


중에서 먼저 숫자(Number)와 문자열(String)의 기본 사용법을 소개하였습니다. 


이번 포스팅에서는 지난 포스팅에 이어서 문자열에 특화되어 문자열 자료형을 다양하게 처리할 수 있는 함수인 문자열 메소드(String Methods) 에 대해서 알아보겠습니다. 


문자열 메소드를 숙지하고 있으면 동일한 목적의 문자열 전처리를 위해 직접 프로그래밍을 하는 것보다 문자열 메소드를 사용한 1~2줄의 코드면 해결되므로 업무 효율도 오르고, for loop 문을 쓰는 것보다 속도도 훨씬 빠릅니다. 


[참고]  메소드 (Method)


내장 함수(Built-in Function)와는 달리 문자열 자료형과 같이 특정 자료형이 가지고 있는 함수를 메소드(Method) 라고 합니다. 메소드는 객체 지향 프로그래밍의 기능에 대응하는 파이썬 용어입니다. 함수와 거의 동일한 의미이지만 메소드는 클래스의 멤버라는 점이 다릅니다. 



평소에 공부해놓고 '아, 문자열 메소드에 이런 기능이 있었지!' 정도는 기억해놓고 있어야 바로 찾아서 쓰기 쉽겠지요? 아래에 문자열 메소드들을 기능에 따라서 그룹핑을 해보았는데요, 저의 경우 len(), find(), lower(), upper(), lstrip(), rstrip(), split(), splitlines(), replace(), join(), zfill() 등을 종종 사용하는 편이네요. 



[ 파이썬 문자열 메소드 (String Methods in Python) ]



이번 포스팅은 https://www.tutorialspoint.com/python/python_strings.htm  사이트에 있는 영문 소개자료를 참고하여 작성하였습니다. 문자열 메소드의 기능 설명만 되어 있어서 좀더 이해하기 쉽도록 예제를 추가로 만들어보았습니다. 

expandtabs(), maketrans() 등 일부 메소드는 제가 써본적도 없고 앞으로 거의 쓸 일이 없을 것 같아서 주관적으로 판단해서 몇 개 빼고 소개하는 것도 있습니다. 


하나씩 예을 들어 살펴보겠습니다. 




1. 문자열 계산 관련 메소드 (String methods based on calculation)


len() : 문자열 길이



# len() : Returns the length of the string

>>> a = 'I Love Python'

>>> len(a)

13

 



 min(), max() : 문자열 내 문자, 혹은 숫자의 최소값, 최대값 (알파벳 순서, 숫자 순서 기반)



# max(str), min(str) : Returns the max, min alphabetical character from the string str

>>> d = 'abc'

>>> f = '123'

>>> 

>>> min(d)

'a'

>>> max(d)

'c'

>>> 

>>> min(f)

'1'

>>> max(f)

'3'

 



 count() :  문자열 안에서 매개변수로 입력한 문자열이 몇 개 들어있는지 개수를 셈 

                (begin, end 위치 설정 가능)



# count() : Counts how many times str occurs in string

>>> a = 'I Love Python'

>>> a.count('o')

2

>>> 

>>> a = 'I Love Python'

>>> a.count('o', 7, len(a)) # count(string, begin, end)

1

>>> 

>>> a.count('k') # there is no 'k' character in 'a' string

0

 





2. 문자열에 특정 문자 들어있는지 여부, 어디에 위치하고 있는지 찾아주는 메소드


  startswith() : 문자열이 매개변수로 입력한 문자열로 시작하면 True, 그렇지 않으면 False 반환



# startswith(): Determines if string or a substring of string

>>> a = 'I Love Python'

>>> a.startswith('I')

True

>>> a.startswith('I Lo')

True

>>> a.startswith('U')

False

 



  endswith() : 문자열이 매개변수로 입력한 문자열로 끝나면 True, 그렇지 않으면 False 반환



# endswith(): Determines if string or a substring of string

>>> a = 'I Love Python'

>>> a.endswith('Python')

True

>>> a.endswith('Pycham')

False

 



 find() : 문자열에 매개변수로 입력한 문자열이 있는지를 앞에서 부터 찾아 index 반환, 없으면 '-1' 반환



# find() : Search forwards, Determine if str occurs in string and return the index

>>> a = 'I Love Python'

>>> a.find('o')

3

>>> a.find('k') # if there is no string, then '-1'

-1

 



  rfind() : 문자열에 매개변수로 입력한 문자열이 있는지를 뒤에서 부터 찾아 index 반환, 없으면 '-1' 반환



# rfind() : Same as find(), but search backwards in string

>>> a = 'I Love Python'

>>> a.rfind('o')

11

 



 index() :  find()와 기능 동일하나, 매개변수로 입력한 문자열이 없으면 ValueError 발생



# index(): Same as find(), but raises an exception if str not found

>>> a = 'I Love Python'

>>> a.index('o')

3

>>> a.index('k') # ValueError: substring not found

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: substring not found

 



 rindex() : index()와 기능 동일하나, 뒤에서 부터 매개변수의 문자열이 있는지를 찾음



# rindex(): Same as index(), but search backwards in string

>>> a = 'I Love Python'

>>> a.rindex('o')

11

>>> a.rindex('k') # ValueError: substring not found

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: substring not found

 





3. 숫자, 문자 포함 여부 확인하는 메소드


  isalnum() : 문자열이 알파벳과 숫자로만 이루어졌으면 True, 그렇지 않으면 False



>>> a = 'I Love Python'

>>> d = 'abc'

>>> e = '123abc'

>>> f = '123'

>>> 

# isalnum() : Returns true if string has at least 1 character and 

#                  all characters are alphanumeric and false otherwise

>>> a.isalnum() # False

False

>>> d.isalnum() # True

True

>>> e.isalnum() # True

True

>>> f.isalnum() # True

True




  isalpha() : 문자열이 알파벳(영어, 한글 등)으로만 이루어졌으면 True, 그렇지 않으면 False



>>> a = 'I Love Python'

>>> d = 'abc'

>>> e = '123abc'

>>> f = '123'

>>> 

# isalpha() : Returns true if string has at least 1 character 

#                 and all characters are alphabetic and false otherwise

>>> a.isalpha() # False (there is space between characters)

False

>>> d.isalpha() # True

True

>>> e.isalpha() # False

False

>>> f.isalpha() # False

False




  isdigit() : 문자열이 숫자만 포함하고 있으면 True, 그렇지 않으면 False, isnumeric()과 동일



>>> a = 'I Love Python'

>>> d = 'abc'

>>> e = '123abc'

>>> f = '123'

>>> 

# isdigit() : Returns true if string contains only digits and false otherwise

>>> a.isdigit() # False 

False

>>> d.isdigit() # False

False

>>> e.isdigit() # False

False

>>> f.isdigit() # True

True




  isnumeric() : 문자열이 숫자로만 이루어져 있으면 True, 그렇지 않으면 False, isdigit()과 동일



>>> a = 'I Love Python'

>>> d = 'abc'

>>> e = '123abc'

>>> f = '123'

>>> 

# isnumeric(): Returns true if a unicode string contains only numeric characters

>>> a.isnumeric() # False

False

>>> d.isnumeric() # False

False

>>> e.isnumeric() # False

False

>>> f.isnumeric() # True

True

 



  isdecimal() : 문자열이 10진수 문자이면 True, 그렇지 않으면 False



>> a = 'I Love Python'

>>> d = 'abc'

>>> e = '123abc'

>>> f = '123'

>>> 

# isdecimal(): Returns true if a unicode string contains only decimal characters

>>> a.isdecimal() # False

False

>>> d.isdecimal() # False

False

>>> e.isdecimal() # False

False

>>> f.isdecimal() # True 

True

 





4. 대문자, 소문자 여부 확인하고 변환해주는 문자열 메소드


  islower() : 문자열이 모두 소문자로만 되어있으면 True, 그렇지 않으면 False



>>> a = 'I Love Python'

>>> g = 'i love python'

>>> h = 'I LOVE PYTHON'

>>> 

# islower(): Returns true if string has at least 1 cased character 

#            and all cased characters are in lowercase and false otherwise

>>> a.islower() # False

False

>>> g.islower() # True

True

>>> h.islower() # False

False

 



  isupper() : 문자열이 모두 대문자로만 되어있으면 True, 그렇지 않으면 False



>>> a = 'I Love Python'

>>> g = 'i love python'

>>> h = 'I LOVE PYTHON'

>>> 

# isupper(): Returns true if string has at least one cased character 

#           and all cased characters are in uppercase and false otherwise

>>> a.isupper() # False

False

>>> g.isupper() # False

False

>>> h.isupper() # True

True

 



  lower() : 문자열 내 모든 대문자를 모두 소문자(a lowercase letter)로 변환



>>> a = 'I Love Python'

>>> 

# lower(): Converts all uppercase letters in string to lowercase

>>> a.lower()

'i love python'




 upper() :  문자열 내 모든 소문자를 모두 대문자(a uppercase letter)로 변환



>>> a = 'I Love Python'

>>> 

# upper(): Converts lowercase letters in string to uppercase

>>> a.upper()

'I LOVE PYTHON'

 



 swapcase() : 문자열 내 소문자는 대문자로 변환, 대문자는 소문자로 변환



# swapcase(): Inverts case for all letters in string

>>> a = 'I Love Python'

>>> a.swapcase() # 'i lOVE pYTHON'

'i lOVE pYTHON'

>>> 

>>> g = 'i love python'

>>> g.swapcase() # 'I LOVE PYTHON' (same as upper())

'I LOVE PYTHON'

>>> 

>>> h = 'I LOVE PYTHON'

>>> h.swapcase() # 'i love python' (same as lower())

'i love python'

 



  istitle() : 문자열이 제목 형식에 맞게 대문자로 시작하고 이후는 소문자이면 True, 그렇지 않으면 False



>>> a = 'I Love Python'

>>> g = 'i love python'

>>> h = 'I LOVE PYTHON'

>>> 

# istitle(): Returns true if string is properly "titlecased" and false otherwise

>>> a.istitle() # True

True

>>> g.istitle() # False

False

>>> h.istitle() # False

False

 



 title() : 문자열을 제목 형식(titlecased)에 맞게 시작은 대문자로, 나머지는 소문자로 변환 



>>> g = 'i love python'

>>> h = 'I LOVE PYTHON'

>>> 

# title(): Returns "titlecased" version of string, that is, 

#          all words begin with uppercase and the rest are lowercase

>>> g.title() # 'I Love Python'

'I Love Python'

>>> h.title() # 'I Love Python'

'I Love Python'

 



  capitalize)=() : 문자열 내 첫번째 문자를 대문자로 변환하고, 나머지는 모두 소문자로 변환



>>> a = 'I Love Python'

>>> g = 'i love python'

>>> h = 'I LOVE PYTHON'

>>> 

# capitalize(): Capitalizes first letter of string

>>> a.capitalize() # 'I love python'

'I love python'

>>> g.capitalize() # 'I love python'

'I love python'

>>> h.capitalize() # 'I love python'

'I love python'

 





5. 공백 존재 여부 확인 및 처리하기 문자열 메소드 


 lstrip() : 문자열의 왼쪽에 있는 공백을 제거



# lstrip() : Removes all leading whitespace in string

>>> b = '      I Love Python'

>>> b.lstrip()

'I Love Python'




  rstrip() : 문자열의 오른쪽에 있는 공백을 제거



# rstrip() : Removes all trailing whitespace of string

>>> c = 'I Love Python      '

>>> c.rstrip()

'I Love Python'

 



  strip() : 문자열의 양쪽에 있는 공백을 제거



# strip() : Performs both lstrip() and rstrip() on string

>>> '     I Love Python     '.strip()

'I Love Python'

 



  isspace() : 문자열이 단지 공백(whitespace)으로만 되어있을 경우 True, 그렇지 않으면 False



# isspace(): Returns true if string contains only whitespace characters and false otherwise

>>> i = '     '

>>> j = '      I Love Python'

>>> 

>>> i.isspace() # True

True

>>> j.isspace() # False

False

 



  center(width) : 총 길이가 매개변수로 받는 문자열폭(width)만큼 되도록 공백을 추가하여 중앙 정렬



# center(): Returns a space-padded string with the original string 

#                centered to a total of width columns

>>> a = 'I Love Python'

>>> a.center(21)

'    I Love Python    '

 





6. 문자열을 나누고, 붙이고, 교체하고, 채우는 문자열 메소드 (split, join, replace, fill)


  split() : 문자열을 구분자(delimiter, separator) 기준에 따라 나누기


split()은 상당히 자주 사용하는 문자열 메소드 입니다. 



# split(): Splits string according to delimiter str (space if not provided) 

#    and returns list of substrings; split into at most num substrings if given

>>> x = 'haha, hoho, hihi'

>>> x.split(sep=',') # as a list ['haha', ' hoho', ' hihi']

['haha', ' hoho', ' hihi']




>>> ha, ho, hi = x.split(sep=',')

>>> ha

'haha'

>>> ho

' hoho'

>>> hi

' hihi'

 



>>> a = 'I Love Python'

>>> a.split(' ') # without arg 'sep='

['I', 'Love', 'Python']

>>> a.split() # default delimiter is space if not provided

['I', 'Love', 'Python'] 

 



  splitlines() : 여러개의 줄로 이루어진 문자열을 줄 별로 구분하여 리스트 생성



# splitlines(): returns a list with all the lines in string, 

#     optionally including the line breaks (if num is supplied and is true)

>>> y = 'haha, \nhoho, \nhihi'

>>> y

'haha, \nhoho, \nhihi'

>>> y.splitlines() # ['haha, ', 'hoho, ', 'hihi']

['haha, ', 'hoho, ', 'hihi']

 



 replace(old, new, max) : old 문자열을 new 문자열로 교체.  단, max 매개변수 있으면, max 개수 만큼만 교체하고 이후는 무시



# replace(old, new): Replaces all occurrences of old in string with new 

#        or at most max occurrences if max given

>>> a = 'I Love Python'

>>> a.replace('Python', 'R')

'I Love R'

>>> 

>>> 

>>> a_2 = 'I Love Python, Python, Python, Python, Python~!!!'

>>> a_2.replace('Python', 'R', 3) # str.replace(old, new, max)

'I Love R, R, R, Python, Python~!!!'




 join() :  여러개의 문자열을 구분자(separator) 문자열을 사이에 추가하여 붙이기


join()은 꽤 자주 쓰는 문자열 메소드 중의 하나입니다. 



# join(): Merges (concatenates) the string representations of elements 

#         in sequence seq into a string, with separator string

>>> mylist = ['I', 'Love', 'Python']

>>> print(mylist)

['I', 'Love', 'Python']

>>> 

>>> mystring = '_'.join(mylist)

>>> print(mystring) # 'I_Love_Python'

I_Love_Python

 



# To concatenate item in list to strings with join() method

>>> mylist_num = [1, 2, 3, 4, 5]

>>> print(mylist_num) # [1, 2, 3, 4, 5]

[1, 2, 3, 4, 5]

>>> 

>>> mylist_str = ''.join(map(str, mylist_num))

>>> print(mylist_str) # 12345

12345

>>> 

>>> '_'.join(map(str, mylist_num)) # '1_2_3_4_5'

'1_2_3_4_5'

 



 zfill(width) : 문자열을 매개변수 width만큼 길이로 만들되, 추가로 필요한 자리수만큼 '0'을 채움



# zfill(width): Returns original string leftpadded with zeros to a total of width characters; 

#      intended for numbers, zfill() retains any sign given (less one zero)

>>> f = '123'

>>> f.zfill(10)

'0000000123' 




 ljust(width[, fillchar]) : 문자열을 매개변수 width만큼 길이로 만들되, 왼쪽은 원본 문자열로 채우고, 

오른쪽에 추가로 필요한 자리수만큼 매개변수 fillchar 문자열로 채움



# ljust(): Returns a space-padded string with the original string left-justified 

#          to a total of width columns

# str.ljust(width[, fillchar])

>>> a = 'I Love Python'

>>> a.ljust(20, 'R')

'I Love PythonRRRRRRR'

 



 rjust(width[, fillchar]) : 문자열을 매개변수 width만큼 길이로 만들되, 오른쪽은 원본 문자열로 채우고, 

 왼쪽에 추가로 필요한 자리수만큼 매개변수 fillchar 문자열로 채움



# rjust(): Returns a space-padded string with the original string right-justified 

#          to a total of width columns

>>> a.rjust(20, 'R')

'RRRRRRRI Love Python'

>>> a.rjust(20, ' ')

'       I Love Python'

 



다음번 포스팅에서는 문자열의 포맷 메소드(string formatting opertor)에 대해서 알아보겠습니다. 


많은 도움 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^



728x90
반응형
Posted by Rfriend
,