Python 알고리즘 주요 라이브러리

Yeom Gyu Hyeon·2022년 4월 23일
0

코테

목록 보기
1/3

리스트

리스트명.pop(인덱스)
리스트명.remove(값)
리스트명.count(3): 3값의 데이터 개수
파이썬 값으로 인덱스찾기
a1 = [1, 1, 1, 2, 3, 4, 5, 6]
print(a1.index(1))
#출력: 0(a1 리스트에서 가장 앞에 있는 1값의 인덱스를 반환해준다)

파이썬에서는 find불가(string에서만 가능)

list_a = [1, 1, 1, 2, 3, 4, 5, 6]
print(list_a.find(1))
#출력: AttributeError: 'list' object has no attribute 'find'

집합

집합명.add(data)
집합명.remove(data)

딕셔너리

키만 모아놓음: 딕셔너리명.keys(A)
값만 모아 놓음: 딕셔너리명.values()
데이터추가: 딕셔너리명['사과'] = 'Apple'
데이터 확인
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

if 'a' in my_dict:
    print("It have the key a")
#출력: It have the key a

값으로 키 찾기

my_dict ={"John":1, "Michael":2, "Shawn":3}
 
list_of_key = list(my_dict.keys())
list_of_value = list(my_dict.values())
 
position = list_of_value.index(1)
print(list_of_key[position])
 
position = list_of_value.index(2)
print(list_of_key[position])

#출력: John
#출력: Michael

값으로 키 찾기 2

aa = {'0': 'AA', '1': 'BB', '2': 'CC'}
bb = {v:k for k,v in aa.items()} #// {'AA': '0', 'BB': '1', 'CC': '2'}
bb.get('CC')
#출력: '2'

딕셔너리 컴프리헨션

string_list = ['A','B','C']
dictionary = {string : i for i,string in enumerate(string_list)}
print(dictionary)
#출력: {'A': 0, 'B': 1, 'C': 2}

내장함수

: min(), max(), sum()

itertools

permutations(data,3): 리스트에서 3개를 뽑아 나열하는 모든 경우를 출력
product: 중복 순열
combinations_with_replacement: 중복조합

heapq

import heapq
h = []
result = []
힙 삽입: heapq.heappush(h, value)
힙 팝: heapq.heappop(h)

bisect

from bisect import bisect_left, bisect_right
a = [1, 2, 4, 4, 8]
print(bisect_left(a, x)) #출력: 2
정렬된 순서를 유지하면서 리스트 a에 데이터 x를 삽입할 가장 왼쪽 인덱스를 찾는 메서드

collections

Counter: 등장 횟수를 세는 기능을 제공 from collections import Counter
counter = Counter(['red', 'blue', 'green', 'blue', 'blue'])
print(dict(counter)) # 사전 자료형으로 변환 list,set도 가능하고 두개가 같은 값을 가진다
#출력: {'red': 1, 'blue': 3, 'green': 1}

math

math.sqrt(7)
math.gcd(21,14): 최대공약수
math.pi
math.e
math.inf: 무한대, -math.inf: 음의 무한대
math.isinf(): 무한대확인

문자열

string.replace("i", "a"): i를 a로 대체
string.find("is"): "is"의 문자의 처음 인덱스 반환
string.count("i"): i의 개수
string.split("a"): a를 기준으로 분리(a문자는 사라짐)
li = ["apple", "banana", "kiwi", "tomato"]
",".join(li) => ,로 연결
li = [1, 2, 3, 4] => 문자열이 아니면 join시 에러발생
아스키코드 변환: chr(65):'A', chr(97):'a', ord('b'): 98, ord('0'): 48

기타

1. zip 함수
print(list(zip([1,2,3], (4,5,6), "abcd")))
#출력: [[1, 4, 'a'], [2, 5, 'b'], [3, 6, 'c']]

zip은 함수 안의 각 리스트, 튜플, 문자열에 대하여 각 요소를 짝지어 주는 함수이다.

2. startswith 함수

print("dfagd".startswith("abcd"))
print("abcde".startswith("abcd"))
#출력: False
#출력: True

startswith는 p2가 p1으로 시작되면 True 아니면 False를 반환한다.

3. list comprehension

profile
개발일지

0개의 댓글