리스트 정렬의 경우
sort나 sorted를 사용하면 된다.
s_list = ['a', 's', 'd', 'f', 'c']
# 방법 1
s_list.sort()
print(s_list) # ['a', 'c', 'd', 'f', 's']
# 방법 2
new_list = sorted(s_list)
print(new_list)
문자열일 경우
join과 sorted를 사용한다.
s = "asdfc"
s.sort() # error
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: 'str' object has no attribute 'sort'
s2 = sorted(s) # ['a', 'c', 'd', 'f', 's']
########## 방법 ##########
s3 = ''.join(sorted(s)) # 'acdfs'
'프로그래밍 언어 > Python' 카테고리의 다른 글
[python] deque 활용법 (0) | 2023.04.25 |
---|---|
[python] 리스트 역순으로 반복문 실행하기 (0) | 2023.04.10 |
[Python] 효율적인 문자열 붙이기 방법(String Concatenate) (0) | 2023.02.21 |
[python] 람다(lambda) 정렬(sort) (1) | 2023.01.14 |
[python] 파이썬 round 함수 사사오입 원칙 (1) | 2023.01.10 |