python/기타

python 기본함수, List 함수, List Comprension

Memory! 2022. 5. 18. 23:09
728x90
반응형

1. List 에 사용 가능한 기본 함수

  • len() : List의 크기를 반환 (List의 개수)
  • max() : List 인자 중 가장 큰 값을 반환
  • min() : List 인자 중 가장 작은 값을 반환
  • sum() : List 내의 인자들의 합을 반환 (List 내 값이 모두 숫자인 경우 가능)
  • sorted() : List를 정렬하여 반환, 기본이 오름차순, 옵션으로 내림찻훈 가능 (reverse=True) 
  • reversed() : List 인자들의 순서를 거꾸로 반환, List()를 통해 다시 List 형태로 변환 해야 함
# List에 사용 가능한 함수들

a = [1,5,6,10,22,11,7,30,28,9]
b = ['a','b','d','it','tistory',11]

len(a) 
10 # 결과 값

max(a)
30 # 결과 값

min(a)
1 # 결과 값

sum(a)
129 # 결과 값

sum(b)
TypeError: unsupported operand type(s) for +: 'int' and 'str' # Error 발생

sorted(a)
[1, 5, 6, 7, 9, 10, 11, 22, 28, 30] # 결과 값

reverse_a = reversed(a)
reverse_a = list(reverse_a)
reverse_a 
[9, 28, 30, 7, 11, 22, 10, 6, 5, 1] # 결과 값

2. List 함수

  • index() : list내에 값이 존재하면 index의 번호를 반환(두개 이상의 경우 처음 index), 없으면 오류를 반환
  • count() : lists내의 해당 데이터 갯수 반환
  • append() : 리스트에 데이터를 추가함 (맨 뒤에 추가됨)
  • insert() : list의 원하는 위치에 data를 삽입
  • remove() : list 에 값 삭제
  • sort() : 리스트를 정렬
# List 함수 알아보기
a = [1,5,6,10,22,11,7,30,28,9]
b = ['a','b','d','it','tistory',11]

a.index(5)
1 # 결과 : 5의 위치 
a.index(55)
ValueError: 55 is not in list # 에러 발생 - a 리스트에 55라는 값이 없음

a.count(5)
2 # 결과 : 5의 개수 2 반환

b.append('insert')
print(b)
['a', 'b', 'd', 'it', 'tistory', 11, 'insert'] # 결과 : 'insert'가 마지막에 추가됨

b.insert(2,'cc')
print(b)
['a', 'b', 'cc', 'd', 'it', 'tistory', 11, 'insert'] # 결과 : index 2에 'cc' 가 추가됨

b.remove('b')
print(b)
['a', 'cc', 'd', 'it', 'tistory', 11, 'insert'] # 결과 : 'b'가 삭제됨

b.remove('b')
ValueError: list.remove(x): x not in list # 결과 : error 발생 - 이미 'b'가 list에 없음

a.sort()
print(a)
[1, 5, 5, 6, 7, 9, 10, 11, 22, 28, 30] # 정렬된 list 반환

a.sort(reverse=True)
print(a)
[30, 28, 22, 11, 10, 9, 7, 6, 5, 5, 1] # 거꾸로 정렬된 list 반환

b.sort()
TypeError: '<' not supported between instances of 'int' and 'str'
# b list에는 숫자와 문자 형태가 같이 있어서 비교가 불가능하다는 에러 발생

3. List Comprension (리스트 컴프리헨션)

  • list를 생성하는 방법 중 하나
  • [] 안에 반복문(for)과 조건문을 이용해서 조건에 맞는 list를 생성할 수 있다
# for를 이용한 list 생성
list_for = []
for i in range(0, 10) :
    list_for.append(i)
print(list_for)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 결과 

# list comprension 이용
list_comp = [i for i in range(10, 20)]
print(list_comp)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] # 결과

# if 사용
list_if = [i for i in range(10, 20) if i % 2 == 0]
print(list_if)
[10, 12, 14, 16, 18] # 결과
728x90
반응형