티스토리 뷰
sum()
Signature: sum(iterable, /, start=0)
Docstring: Return the sum of a 'start' value (default: 0) plus an iterable of numbers
Type: builtin_function_or_method
sum()
- python 내장 함수
- 반복가능(iterable)한 type을 전부 더해준다.
= 반복가능(iterable)한 type :
- String, List, Tuple, Dictionary, Range, Set
- 단, String은 sum()을 지원하지 않는다. - 'start' value를 우선으로 하여 item을 다 합한 값을 반환한다.
- iterable =
→ 반복가능(iterable)한 type을 입력 받는다.
→ 파라메터에 입력값이 빈값 이라면 0을 출력한다.
= sum([]) == 0 - start =
→ 가장 먼저 더해줄 item
→ default: 0
사용예제
sum(str) #불가능
str_ = 'abc'
sum_str = sum(str_)
print(sum_str)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [163], in <cell line: 2>() 1 str_ = 'abc' ----> 2 sum_str = sum(str_) 3 print(sum_str) TypeError: unsupported operand type(s) for +: 'int' and 'str'
- unsupported operand type(s) for +: 'int' and 'str'
- start 파라미터의 default는 0이기 때문에 발생하는 문제이다.
자세히 설명하면 int와 str은 더할 수 없기 때문에 발생하는 오류 이다. - start 파라미터를 문자열(str)로 변경하여 구현 하면 작동될까?
- 결론 : 아니다.
str_ = 'abc'
sum_str = sum(str_, '')
print(sum_str)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [164], in <cell line: 2>() 1 str_ = 'abc' ----> 2 sum_str = sum(str_, '') 3 print(sum_str) TypeError: sum() can't sum strings [use ''.join(seq) instead]
- sum() 은 문자열(str)을 더할 수 없으며,
대신 ''.join(seq)과 같은 방식을 추천하고 있습니다.
sum(tuple)
tuple_ = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
tuple_sum = sum(tuple_)
print(tuple_sum)
55
sum(list) : 1차원 리스트, 2차원 이상의 리스트
- 1차원 리스트
# 1차원 리스트
list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list_sum = sum(list_)
print(list_sum)
55
- 2차원 리스트
# 2차원 리스트
list_ = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
list_sum = sum(list_)
print(list_sum)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [166], in <cell line: 3>() 1 # 2차원 리스트 2 list_ = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] ----> 3 list_sum = sum(list_) 4 print(list_sum) TypeError: unsupported operand type(s) for +: 'int' and 'list'
- unsupported operand type(s) for +: 'int' and 'list'
- start 파라미터의 default는 0이기 때문에 발생하는 문제이다.
자세히 설명하면 int와 list는 더할 수 없기 때문에 발생하는 오류 이다. - start 파라미터를 list로 변경하여 구현 하면 작동될까?
- 결론 : 가능하다.
(아래 이어지는 내용에서 이를 설명하고자 한다.)
# 2차원 리스트
list_ = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
list_sum = sum(list_, []) # sum(list_, list())도 가능하다
print(list_sum)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum()함수의 연산을 풀어 구현하면, 아래 구현 처럼 예상해 볼 수 있다.
# start 파라메터를 default로 사용했을 경우
0 + [1, 2] + [3, 4] + [5, 6] + [7, 8] + [9, 10]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [176], in <cell line: 1>() ----> 1 0 + [1, 2] + [3, 4] + [5, 6] + [7, 8] + [9, 10] TypeError: unsupported operand type(s) for +: 'int' and 'list'
# start 파라메터를 [], list()로 사용했을 경우
# []
[] + [1, 2] + [3, 4] + [5, 6] + [7, 8] + [9, 10]
# list()
list() + [1, 2] + [3, 4] + [5, 6] + [7, 8] + [9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum(dict) : .keys(), .values(), .items()
- 딕셔너리 선언
# key가 문자열(str)인 경우
dict_keys_str = {'ㄱ': 1, 'ㄴ': 2, 'ㄷ': 3, 'ㄹ': 4}
# key가 정수(int)인 경우
dict_keys_int = {1: 'ㄱ', 2: 'ㄴ', 3: 'ㄷ', 4: 'ㄹ'}
# key, value 둘다 정수(int)인 경우
dict_all_int = {1: 10, 2: 20, 3: 30, 4: 40}
- sum(dict)
sum(dict_keys_str) # TypeError 위 sum(str)과 같은 연산
sum(dict_keys_int) # 10
sum(dict_all_int) # 10
- 선언된 딕셔너리의 key를 기준으로 연산된다.
- 결과는 위 주석과 같다.
- sum(dict.keys())
sum(dict_keys_str.kyes()) # TypeError 위 sum(str)과 같은 연산
sum(dict_keys_int.kyes()) # 10
sum(dict_all_int.kyes()) # 10
- sum(dict)와 같은 연산이 진행 된다.
- 결과는 위 주석과 같다.
- sum(dict.values())
sum(dict_keys_str.values()) # 10
sum(dict_keys_int.values()) # TypeError 위 sum(str)과 같은 연산
sum(dict_all_int.values()) # 100
- 선언된 딕셔너리의 value를 기준으로 연산된다.
- 결과는 위 주석과 같다.
- sum(dict.items())
sum(dict_keys_str.items())
sum(dict_keys_int.items())
sum(dict_all_int.items())
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [224], in <cell line: 1, 2, 3>() ----> 1 sum(dict_keys_str.items()) ----> 2 sum(dict_keys_int.items()) ----> 3 sum(dict_all_int.items()) TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
- unsupported operand type(s) for +: 'int' and 'tuple'
tuple? : type(dict().items()) dict_items에 관해서는 따로 정리해서 올릴것
sum(dict_keys_str.items(), ()) # ('ㄱ', 1, 'ㄴ', 2, 'ㄷ', 3, 'ㄹ', 4)
sum(dict_keys_int.items(), ()) # (1, 'ㄱ', 2, 'ㄴ', 3, 'ㄷ', 4, 'ㄹ')
sum(dict_all_int.items(), ()) # (1, 10, 2, 20, 3, 30, 4, 40)
- 결과는 위 주석과 같다.
sum(set)
set_ = {1,1,2,3,4,5,6,7,8,9,10,10}
set_sum = sum(set_)
print(set_sum)
55
- 집합을 사용하여 고유(unique)한 값의 합을 구할 수 있다.
sum(range(n))
range_ = range(1, 10+1)
range_sum = sum(range_)
print(range_sum)
# print(sum(range(1, 10+1)))
55
- range()의 경우 또한 반복가능(iterable)한 type이기 때문이 위와 같이 연산이 가능하다.
sum()
Python으로 구현
# sum 함수 구현 기존 함수의 오버라이딩을 피하기 위해 sum_으로 명명
def sum_(iterable, start=0):
result = start
if type(result) is str:
print('문자열의 합 연산은 다른 함수를 사용해 주세요')
return
for item in iterable:
result += item
return result
'Python > Analysis to Python' 카테고리의 다른 글
[f-string] : 문자열 포맷팅 딥하게 알아보기 + Tip (0) | 2022.07.27 |
---|---|
[split] : 문자열을 나눠주는 함수 (0) | 2022.07.10 |
[append an element in list] : 속도 비교(performance testing ) (0) | 2022.06.07 |
[eval, exec] : 문자열을 코드로 실행하는 함수 (0) | 2022.05.30 |
[sort, sorted] : 정렬 함수 (0) | 2022.05.29 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- sad asd
- 파이썬
- arguments
- conda
- 백준
- underscore
- 덮어쓰기
- 이중 프린트
- sdsad
- 변수 덮어쓰기
- asd ad
- Python
- sep=
- 콘다
- 재귀함수 이해
- _의미
- 재귀?
- anaconda
- 이스케이프 코드
- list comprehension
- 파이썬 변수
- recursive function
- 재귀함수 설명
- matplotlib
- print()
- parameters
- recursive
- _meaning
- d asd asd
- 연산속도
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함