Python 기초 함수 정리(1)

hjseo-dev·2021년 6월 7일
0

Python 알고리즘

목록 보기
7/13
post-thumbnail

1. 값이 모두 다른 리스트 찾기

set함수로 중복된 것을 제거한 후, 길이를 반환

def all_unique(list):
    return len(list) == len(set(list))

a = [1,2,3,4,5,6]
b = [2,2,4,4,1,2,5]

print(all_unique(a))  # True
print(all_unique(b))  # False

2. 단어의 첫글자를 대문자로 바꾸기

title() 함수를 쓰면 문자의 첫글자가 바뀐다.

def capitalize_every_sord(s):
    return s.title()
    
print(capitalize_every_sord('hello world!')) # Hello World!

3. 섭씨온도에서 화씨온도로 바꾸기

수식을 알아보자! C = Fx1.8 + 32

def celsius_to_hahrenheit(celsius):
    return ((celsius * 1.8) + 32)

print(celsius_to_hahrenheit(180)) # 356.0

4. false 값 제거하기

filter함수로 None 값을 걸면 '', False, 0, None 이 제거된다.

def compact(lst):
    return list(filter(None, lst))
print(compact([0,1,False,2,'',3,'a','s',34]))  # [1, 2, 3, 'a', 's', 34]

5. 리스트 안에 주어진 숫자가 몇 개 있는지 확인하기

list 컴프리헨션으로 타입이 같은 것과 값이 같은 것을 찾아 반환

def count_occurrences(lst, val):
    return len([x for x in lst if x == val and type(x) == type(val)])

print(count_occurrences([1,1,2,1,2,3],1))  # 3

6.degree에서 radian으로 변환

from math import pi

def degrees_to_rads(deg):
    return (deg*pi)/180.0

print(degrees_to_rads(180))

7. 두 리스트의 차집합 구하기

비교할 대상인 b를 set함수로 중복 제거 후 a에 있는지 본다.

def difference(a,b):
    _b = set(b)
    return [item for item in a if item not in _b]

print(difference([1,2,3],[1,2,4]))  # 3

8. int형 숫자를 문자형 리스트로 변환

map을 사용해 int형을 모두 str로 바꾸고 저장한다

def digitize(n):
    return list(map(int, str(n)))

print(digitize(123))

9. 왼쪽/오른쪽에서 부터 n개의 값이 제거된 리스트를 반환하기

리스트 자르기 사용! 반대인 경우도 포함

def drop(a,n=1):
    return a[n:]
    
print(drop([1,2,3]))    # [2,3]
print(drop([1,2,3],2))  # [3]
--------------------------------
# 반대의 경우
def drop_right(a,n=1):
    return a[:-n]
    
print(drop([1,2,3]))    # [1,2]
print(drop([1,2,3],2))  # [1]

10. 리스트에서 n번째 수만 출력하기

def every_nth(lst, nth):
    return lst[nth-1::nth]

print(every_nth([1,2,3,4,5,6], 2))  #[2,4,6]

0개의 댓글