Python - 내장함수 Part 1

23288 단어 pythonpython

조합 생성

from itertools import combinations

a = [1,2,3]
combi = combinations(a,2)    
print(list(combi))

[(1,2),(1,3),(2,3)]

순열 생성

from itertools import permutations

a = [1,2,3]
permute = permutations(a,2)
print(list(permute))

[(1,2),(1,3),(2,1),(2,3),(3,1),(3,2)]

문자열 <-> 배열

str = 'python'
strToArr = list(str) // ['p', 'y', 't', 'h', 'o', 'n']

timeStr = "20:23:00"
timeArr = timeStr.split(':') // ['20', '23', '00']

문자열 -> 배열
timeList = ['20', '23', '00']
timeArr = ':'.join(timeList) // '20:23:00'

배열 -> 문자열

slice

array[ x:y ] : x인덱스부터 y - 1 인덱스까지 잘라서 반환한다.
array[:] : 해당 배열을 전부 똑같이 반환. 원 배열을 건드리지 말아야 할때 유용

list = [ 0, 1, 2, 3, 4, 5 ]
copyList = list[:] # [ 0, 1, 2, 3, 4, 5 ]
list = list[ 1:3 ] # [1, 2]

거듭 제곱

a = 3
b = 5

print(a ** b) # 243
print(pow(a, b)) # 243

문자열 <-> 숫자

num = 100.00001
str(num) # '100.0' 소수점 한 자리
repr(num) # '100.00001' 모든 소수점 출력


str = '100'
int(str) # 100

누적

list = [10, 20, 30] # sum은 문자열 불가
print(sum(list)) # 60
from functools import reduce

list1 = [10, 20, 30] # 문자열끼리 혹은 숫자끼리 합가능
list2 = ['a', 'b', 'c']
list3 = ['a', 20, 30] # 불가

print(reduce(lambda x, y: x + y, list1)) # 60
print(reduce(lambda x, y: x + y, list2)) # 'abc'

삼항연산자

a = 10
b = 10
result = (a-b) if a == b else (a+b) # 0 
# (조건식이 True일 때의 값) if (조건문) else (False일 때 값)

반복문에서 배열의 인덱스, 값

list = [0, 10, 20, 30]
for (index, value) in enumerate(list): # 반복가능한 객체 모두 해당, 튜플도 가능 
	print(index, value)

# 0 0
# 1 10
# 2 20
# 3 30

for (index, value) in enumerate(list, start = 2):
	print(index, value) # start = x => 원하는 인덱스 x 부터
    
# 2 20
# 3 30 

반복문으로 배열에 값 할당(생성)

list = [value for value in range(5)]
print(list) # [0, 1, 2, 3, 4]
list = [[0 for j in range(2)] for i in range(3)]
print(list) # [[0 ,0 ], [0, 0], [0, 0]]
a = [2, 1, 2, 3, 5]
b = [] # 전체 가장 바깥쪽 대괄호

for i in a:
    line = []
    for j in range(i)
    	line.append(0)
    b.append(line)

print(b) # [[0, 0], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0, 0]]

map

a = [-3.3, 7.8, 5.2, 2.9] # map은 리스트에서 사용
b = list(map(int, a))
c = list(map(lambda x: x + 1, a))
print(b) # [-3, 7, 5, 2]
print(c) # [-2.3, 8.8, 6.2, 3.9]
# map( 연산할 내용, 해당 배열)

num = [10, 20, 30, 40]
num = list(map(str, num))
print(num) # 	['10', '20', '30', '40']

참고)

순열, 조합
https://potensj.tistory.com/110
https://medium.com/@hckcksrl/python-permutation-combination-a7bf9e5d6ab3

문자열 <-> 배열, slice
https://wayhome25.github.io/python/2017/02/26/py-14-list/

거듭 제곱
https://blockdmask.tistory.com/377

문자열 <-> 숫자
https://webisfree.com/2017-11-11/python-숫자를-문자로-문자를-숫자로-타입바꾸기

삼항연산자
https://blueshw.github.io/2016/01/22/python-conditional-ternary-operator/

반복문 배열의 인덱스, 값
https://dojang.io/mod/page/view.php?id=2283

반복문으로 배열에 값 할당
https://blueshw.github.io/2016/01/22/python-conditional-ternary-operator/
https://dojang.io/mod/page/view.php?id=2293

map
https://dojang.io/mod/page/view.php?id=2286
https://wikidocs.net/22803

좋은 웹페이지 즐겨찾기