자료구조&알고리즘/프로그래머스
[프로그래머스] Lv.0 문자열 정렬하기 (1) python (sorted)
celinayk
2024. 5. 6. 00:05
반응형
def solution(my_string):
ans=[]
for i in my_string:
if i.isdigit():
ans.append(int(i))
return sorted(ans)
처음에 return을 할때
ans.sort()
라고 했는데 자꾸 오류가 났다
알고보니 반환값이 null이엇는데
python에서 list.sort() 메소드는 리스트를 정렬하되 반환값이 None입니다. 이는 sort()가 리스트를 "in-place"로 정렬한다는 의미로, 리스트 자체는 변경되지만, 반환값은 없습니다.
그렇다고 한다
그래서 해결방법
ans.sort() # 리스트를 정렬
return ans # 정렬된 리스트 반환
이렇게 하던가
sorted라는걸 쓰면된다
새로운 정렬된 리스트를 만들어서 반환해주는 함수이다
첫번째 인자 - 이터러블 객체 (list, dict, tuple 등)
두번째 인자 - 정렬을 결정할 함수를 지정
세법째 인자 - default는 오름차순
sorted(iterable, key=key, reverse=reverse)
sort()
- 기존의 리스트를 정렬한다(modifies the list in-place)
- 리스트 내에서만 정의될 수 있다(list.sort() method is only defined for lists)
sorted()
- 새로운 정렬된 리스트를 만든다.(builds a new sorted list from an iterable)
- the sorted() function accepts any iterable.