n진수 ⇒ 10진수로 변환

  • int(string, n진수) : string을 n진수값으로 간주하고 결과값을 10진수로 반환
  • 인자로는 n진수를 문자열로 넣고 결과값은 int로 출력함
  • 진수를 생략하면 n진수를 10진수로 간주하여 문자열을 그냥 숫자로 바꿈
print(int('101',2))
>>> 5
print(int('101'))
>>>101
print(int('202',3))
>>> 20
print(int('303',4))
>>> 51
print(int('404',5))
>>> 104
print(int('505',6))
>>> 185
print(int('ACF',16))
>>> 2767

 

10진수 ⇒ 2, 8, 16진수로 변환

  • 2, 8, 16진수는 bin(), oct(), hex() 함수를 지원함
  • 입력값은 int이지만, 결과값은 string으로 반환함
  • 2진수는 앞에 0b, 8진수는 앞에 0o, 16진수는 앞에0x를 붙혀서 반환함
print(bin(110))
>>> 0b1101110
print(oct(110))
>>> 0o156
print(hex(110))
>>> 0x6e

# 앞에 진수를 나타내는 글자 제외하기
print(bin(110)[2:])
>>> 1101110
print(oct(110)[2:])
>>> 156
print(hex(110)[2:])
>>> 6e

 

10진수 ⇒ n진수로 변환

  • int 같은 함수가 없기 때문에 코드작성이 필요함
def solution(n, q):    # n: 10진수,  q : 변환할 진수   int -> str
    answer = ''
    while n >0:
        a = n%q
        answer = str(a) + answer
        n = n//q
    return answer 

print(solution(45,3))
>>> 1200

 

n진수 ⇒ n진수로 변환

  • 바꾸기 전 n진수를 int()함수를 이용해서 10진수로 만들고(str → int), 위에서 만든 solution함수를 이용해서 바꿀 n진수로 바꿈(int → str)
print(solution(int('c',16),4)) # 16진수인 C를 4진수로 바꾸는것
>>> 30
print(solution(int('4',6),3))  # 6진수인 4를 3진수로 바꾸는것
>>> 11
print(solution(int('21',3),7)) # 3진수인 21을 7진수로 바꾸는것
>>> 10
print(solution(int('15',9),5)) # 9진수인 15를 5진수로 바꾸는것
>>> 24

dictionary[key] = v ⇒ key 라는 곳에 v 값 삽입 : O(1)

del dictionary[key] ⇒ key 라는 곳을 삭제 :  O(1)

dictionary[key] ⇒ key 라는 곳에 있는 v 값 조회 : O(1)

ex = {1:'가', 2:'나', 3:'다'}
ex[4] = '라'  # 삽입  O(1)
print(ex) >>> {1: '가', 2: '나', 3: '다', 4: '라'}

del ex[2]  # 삭제 O(1)  주의! remove가 아닌 del을 사용해야 한다.
print(ex)  >>>  {1: '가', 3: '다', 4: '라'}

print(ex[3])  # 조회 O(1) 
>>> 다

 

딕셔너리는 중복된 key값을 가질 수 없다. 중복된 key값을 쓰면 하나를 제외한 나머지는 무시된다.

a = {1:'a', 1:'b'}
print(a)
>>>{1: 'b'}

 

dic.get(key) : key값에 대응하는 value값을 출력한다. 이는 dic[key]와 같으나 만약 없는 key값을 출력하라고 하면 dic[key]는 error를 출력하고, dic.get(key)는 None을 출력함. 만약 해당 key가 없을 때 반환되는 값을 바꾸고 싶다면, get() 메소드의 두번째 인자로 주면 됨. 

ex = {1:'가', 2:'나', 3:'다'}

print(ex.get(1))
>>> 가
print(ex[1])
>>> 가

print(ex[4])
>>> KeyError
print(ex.get(4))
>>> None
print(ex.get(4,0))
>>> 0

 

리스트나 튜플을 딕셔너리로 만들기

list1 = ['a','b','c','d','e']
list2 = [1,2,3,4,5]
li = []

for x,y in zip(list1, list2):
    li.append((x,y))
print(li)
>>> [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]


dic1 = dict(li)
print( dic1 ) # 리스트의 원소가 튜플이나 리스트로 길이가 2일 때 dict()를 하면 앞에 것은 key , 뒤에 것은 value가 된다.
>>> {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}


# 좀 더 빠른 방법
dic2 = dict(zip(list2, list1))
print( dic2 )
>>> {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

 

딕셔너리에서 값을 확인 하는 방법에는 딕셔너리.keys(), 딕셔너리.items(), 딕셔너리.values()가 있다. 주의할 것은 ()를 안하면 객체가 생성되지 않는다. 또한 모두 s가 붙는 복수형이라는 것을 잊지 말자.

     s = {'1':'a', '2':'b'} 
     s.keys()                         
     >>> dict_keys(['1', '2']) 
     s.keys 
     >>> <function dict.keys>
     

     s.values()                       
     >>> dict_values(['a', 'b'])
     s.values 
     >>> <function dict.values>


     s.items()                                    
     >>> dict_items([('1', 'a'), ('2', 'b')])    
     s.items
     >>> <function dict.items>

 

for 문 혹은 if 문에서 딕셔너리 이름을 쓰면 key값만 나오게 된다.

s = {'1':'a', '2':'b'} 

for i in s:                              
    print(i, end = ' ')                                              
>>> 1 2                                                                    

for i in s.keys():
    print(i, end = ' ')
>>> 1 2



if '1' in s:
    print(True)
>>> True 

if '1' in s.keys():
    print(True)
>>> True

 

만약 for문 혹은 if문에서 value값을 찾고 싶거나 item 값을 찾고 싶으면 .values() 혹은 .items()를 써야 한다.

ex) s = {'1':'a', '2':'b'} 

for i in s.values():
    print(i, end = ' ')
>>> a b

for i in s.items():
    print(i, end = ' ')
>>> ('1', 'a') ('2', 'b')



if 'a' in s.values():
    print(True)  
>>> True

if ('1','a') in s.items():
    print(True)
>>>> True

 

딕셔너리 정렬하기

dic = {'toy': 70, 'snack': 200, 'python': 10}
print(dic)
>>> {'toy': 70, 'snack': 200, 'python': 10}

 

1. 딕셔너리에 정렬을 하면 key값을 기준으로 key값을 정렬한 후 key값만 리스트로 출력함 이때, 주의할 점은 문자열을 정렬할때 정렬 순서는 문자열의 길이가 아닌 사전식 배열이 정렬의 기준임

print( sorted(dic) )
>>> ['python', 'snack', 'toy'] # 사전식 정렬

print( sorted(dic, reverse= True) )
>>> ['toy', 'snack', 'python'] # 사전식 배열의 내림차순으로 정렬

 

딕셔너리를 key값을 기준으로 정렬한 후 딕셔너리를 출력하는 방법
⇒ dic.items()를 정렬하면 key값을 기준으로 정렬됨. 이를 이용하면 key값을 기준으로 정렬된 딕셔너리를 출력할 수 있음

print( sorted(dic.items()) )
>>> [('python', 10), ('snack', 200), ('toy', 70)]


print( dict(sorted(dic.items())) )
>>> {'python': 10, 'snack': 200, 'toy': 70}

print( dict(sorted(dic.items(), reverse = True)) )
>>> {'toy': 70, 'snack': 200, 'python': 10} # key값을 기준으로 사전식 배열의 내림차순으로 정렬한 딕셔너리

 

3. 딕셔너리를 value값을 기준으로 정렬한 후 딕셔너리를 출력하는 방법
⇒ dic.items()를 정렬하면 value값을 기준으로 정렬됨. 이를 이용하면 value값을 기준으로 정렬된 딕셔너리를 출력할 수 있음

print( sorted(dic.items(), key = lambda x:x[1]) )
>>>  [('python', 10), ('toy', 70), ('snack', 200)]


print( dict(sorted(dic.items(), key = lambda x:x[1])) )
>>> {'python': 10, 'toy': 70, 'snack': 200}


print( dict(sorted(dic.items(), key = lambda x:x[1], reverse = True)) )
>>> {'snack': 200, 'toy': 70, 'python': 10}

 

4. 딕셔너리를 key값의 문자열 길이를 기준으로 정렬하는 방법

print( sorted(dic, key = lambda x: len(x)) )  # 딕셔너리를 sort하면 key값을 기준으로 정렬됨. 이때 lambda를 써서 key값의 문자열 길이를 기준으로 정렬할 수 있음
>>> ['toy', 'snack', 'python']

print( sorted(dic, key = lambda x: len(x), reverse = True) )
>>> ['python', 'snack', 'toy']

print( sorted(dic.items(), key = lambda x: len(x[0])) )
>>> [('toy', 70), ('snack', 200), ('python', 10)]

print( sorted(dic.items(), key = lambda x: len(x[0]), reverse = True) )
>>> [('python', 10), ('snack', 200), ('toy', 70)]


print( dict(sorted(dic.items(), key = lambda x: len(x[0]))) ) # 딕셔너리의 key값의 문자열 길이를 기준으로 정렬한 딕셔너리
>>> {'toy': 70, 'snack': 200, 'python': 10}
print( dict(sorted(dic.items(), key = lambda x: len(x[0]), reverse = True)) )
>>>  {'python': 10, 'snack': 200, 'toy': 70}

Counter()

  1. 데이터의 갯수를 count할 때 사용함.
  2. 주로 리스트나 튜플, 문자열의 원소의 수를 count할 때 사용함.
  3. 파이썬의 collections 모듈의 Counter클래스를 사용한다.
  4. 결과값은 딕셔너리 형태로 return함
  5. 일반적인 딕셔너리 형태처럼 key값을 보고 싶으면 .keys()을 쓴다. value값을 보고 싶을 땐 .values()를 쓴다.
    하지만 print 될때는 dict_keys(), dict_values() 형태로 나오기 때문에 값들만 보고 싶으면 list() 를 쓰면 됨. 만약 keys() 혹은 values()없이 딕셔너리 형태일때 list를 쓰면 key값을 출력함
    .items()를 쓰면 (key, value)형태의 튜플을 원소로 하는 리스트를 출력함. 다만, dict_items() 형 태로 출력함. 값들만 출력하고 싶을 때는 list()를 쓴다.

리스트의 원소 count

from collections import Counter

data = [2, 2, 2, 1, 1, 3, 3, 4]

make_dict = Counter(data)



print(make_dict)
>>> Counter({2: 3, 1: 2, 3: 2, 4: 1})

print(make_dict.keys())
>>> dict_keys([2, 1, 3, 4])

print(list(make_dict.keys()))
>>> [2, 1, 3, 4]

print(make_dict.values())
>>> dict_values([3, 2, 2, 1])

print(list(make_dict.values()))
>>> [3, 2, 2, 1]

print(list(make_dict))
>>>  [2, 1, 3, 4]  # Counter()에 list()를 쓰면 key값을 출력함

print(make_dict.items())
>>> dict_items([(2, 3), (1, 2), (3, 2), (4, 1)])  # (key, value)

print(list(make_dict.items()))
>>> [(2, 3), (1, 2), (3, 2), (4, 1)]

 

문자열 원소 count

from collections import Counter

s = "hello python"

make_dict = Counter(s)

print(make_dict)
>>> Counter({'h': 2, 'e': 1, 'l': 2, 'o': 2, ' ': 1, 'p': 1, 'y': 1, 't': 1, 'n': 1})

print(make_dict.keys())
>>> dict_keys(['h', 'e', 'l', 'o', ' ', 'p', 'y', 't', 'n'])

print(list(make_dict.keys()))
>>> ['h', 'e', 'l', 'o', ' ', 'p', 'y', 't', 'n']

print(make_dict.values())
>>> dict_values([2, 1, 2, 2, 1, 1, 1, 1, 1])

print(list(make_dict.values()))
>>> [2, 1, 2, 2, 1, 1, 1, 1, 1]

print(make_dict.items())
>>> dict_items([('h', 2), ('e', 1), ('l', 2), ('o', 2), (' ', 1), ('p', 1), ('y', 1), ('t', 1), ('n', 1)])

 

most_common() : 빈도수가 높은 상위 원소들을 (key, value) 형태로 반환

⇒ ()를 쓰는걸 주의하자! 안쓰면 bound method Counter.most_common of Counter와 함께 (key, value)쌍으로 출력되지 않음

from collections import Counter

Counter('abbbbbbcccddddaaaa')
>>> Counter({'a': 5, 'b': 6, 'c': 3, 'd': 4})

Counter('abbbbbbcccddddaaaa').most_common(1)  # 빈도수가 가장 높은 하나만 출력함
>>> [('b', 6)]

Counter('abbbbbbcccddddaaaa').most_common(2)   # 빈도수가 가장 높은 두개만 출력함
>>> [('b', 6), ('a', 5)]

Counter('abbbbbbcccddddaaaa').most_common()    # most_common()안에 인자를 안써주면 모든 key값을 value값의 빈도순으로 나열함
>>> [('b', 6), ('a', 5), ('d', 4), ('c', 3)]

Counter('abbbbbbcccddddaaaa').most_common  # ()를 안써줬을 때
>>> <bound method Counter.most_common of Counter({'b': 6, 'a': 5, 'd': 4, 'c': 3})>

 

두 count를 더하기(+), 뺴기 (-) : value값을 더하거나 뺀다.(주의! 합집합, 차집합과 다름)

from collections import Counter

answer1 = Counter(['kim', 'park', 'kim', 'kim'])
print(answer1)
>>> Counter({'kim': 3, 'park': 1})

answer2 = Counter(['Jung', 'kim', 'kim'])
print(answer2)
>>> Counter({'kim': 2, 'Jung': 1})

print(answer1 +answer2)
>>> Counter({'kim': 5, 'park': 1, 'Jung': 1})

print(answer1 - answer2)
>>> Counter({'kim': 1, 'park': 1})

print(answer2 - answer1)
>>> Counter({'Jung': 1}) # count가 마이너스가 되는 것은 결과에서 뺌

 

&(교집합) 과 |(합집합)

from collections import Counter

answer1 = Counter(['kim', 'park', 'kim', 'kim'])
print(answer1)
>>> Counter({'kim': 3, 'park': 1})

answer2 = Counter(['Jung', 'kim', 'kim'])
print(answer2)
>>> Counter({'kim': 2, 'Jung': 1})


print(answer1 & answer2)
>>> Counter({'kim': 2})

print(answer1 | answer2)
>>> Counter({'kim': 3, 'park': 1, 'Jung': 1})

 

a.substract(b)

Counter()의 객체인 a에서 b의 count 값을 뺌. 단 이때는 위에서 빼기(-)와 달리 Count에 음수가 들어갈 수 있음. 단 이때는 빼기(-)와 달리 다시 값을 출력 해야만 결과가 보임

from collections import Counter

answer1 = Counter(kim=3 ,park=1)  # 위와 같은 결과임. ''을 안쓰는 것 주의. 위와 달리 리스트를 안쓰는 것에 주의!
print(answer1)
>>> Counter({'kim': 3, 'park': 1})

answer2 = Counter(kim=2, Jung=1)  # 위와 같은 결과임. ''을 안쓰는 것 주의. 위와 달리 리스트를 안쓰는 것에 주의!
print(answer2)
>>> Counter({'kim': 2, 'Jung': 1})

answer1.subtract(answer2)
print(answer1)
>>> Counter({'kim': 1, 'park': 1, 'Jung': -1})

answer2.subtract(answer1)
print(answer2)
>>> Counter({'kim': -1, 'Jung': 1, 'park': -1})

 

elements() 

카운트된 수만큼 원소를 반환. 단, 결과를 <itertools.chain at 0x7f0cffe49610> 형태로 출력하기 때문에 값을 보고 싶으면 list()를 해준다. 단, count된게 음수이면 출력하지 않는다.

cnt = Counter('abbbbbbcccddddaaaa')
print(cnt.elements())
>>>  <itertools.chain object at 0x7f0cf7e54cd0>

print(list(cnt.elements()))
>>>  ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd']
from collections import Counter

answer1 = Counter(kim=5 ,park=2) 
answer2 = Counter(kim=2, Jung=1)
answer1.subtract(answer2)
print(answer1)
>>> Counter({'kim': 3, 'park': 2, 'Jung': -1})


print(list(answer1.elements()))
>>>  ['kim', 'park', 'park']

 

dictionary를 이용하여 Counter 흉내내기

def countLetters(word):
    counter = {}
    for letter in word:
        if letter not in counter:
            counter[letter] = 0
        counter[letter] += 1
    return counter

countLetters('hello world')
>>> {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

string.split(sep = None) : sep를 구분자 문자열로 사용하여 문자열에 있는 단어들을 리스트의 원소로 만든 후, 문자열을 리스트로 출력함

  • sep = None이 default값임. string.split()인 경우( default인 경우 ) 연속된 공백 문자는 단일한 구분자로 간주함. 또한 문자열이 선행이나 후행 공백을 포함해도 결과 리스트는 시작과 끝에 빈 문자열을 포함하지 않음
    ex)   'a       b'.split()  # 공백 7칸     >>>  ['a', 'b']
            ' a       b '.split() # 공백 7칸    >>>  ['a', 'b']
  • default값이 아닌 sep가 주어지면, 연속된 구분자는 묶이지 않고 빈 문자열을 구분하는 것으로 간주함
    ⇒ 즉, 리스트를 생성할 때 연속된 구분자 -1개 만큼의 빈 문자열이 원소로 생김
    ex)   'a       b'.split(' ')  # 공백 7칸   >>>   ['a', '', '', '', '', '', '', 'b']  # 빈 문자열 원소 6개
            ‘a,,,,,,,b'.split(',') # 쉼표 7개  >>>   ['a', '', '', '', '', '', '', 'b']  # 빈 문자열 원소 6개
  • 공백이 나오는 문자열에 리스트함수를 쓸 경우 vs split( ‘ ‘ ) vs split() 
    ⇒ string.split()을 쓰면 빈 문자열이 생기지 않고 리스트가 생성됨
    ⇒ string.split(' ')을 쓰면 연속된 공백 -1개 만큼의 빈 문자열이 원소로 생겨난 리스트가 출력됨
    ⇒ list(string)을 쓰면 연속된 공백 만큼의 문자열이 원소로 생겨난 리스트가 출력됨
    ex)   'a       b'.split()      # 공백 7칸 >>> ['a', 'b']     # 빈 문자열 원소 0 개
            'a       b'.split(' ')   # 공백 7칸 >>> ['a', '', '', '', '', '', '', 'b']            # 빈 문자열 원소 6개
            list('a       b')         # 공백 7칸 >>> ['a', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'b']  # 빈 문자열 원소 7개

+ Recent posts