Python

[python3] join() , sorted() 함수

구씨언니 2021. 2. 3. 01:17
반응형

1. join() 

: iterable 한 모든 아이템을 한 개의 string 으로 바꿔줍니다.

seperator 역할을 하는 string이 필요합니다.

seperator_string.join(iterable)

 

예제)

myTuple = ("John", "Peter", "Vicky")

# 튜플을 한 개의 string으로 바꿔준 것을 x에 대입함
x = "#".join(myTuple) 

print(x)


"""
실행 결과:
John#Peter#Vicky
"""

 

참고: www.w3schools.com/python/ref_string_join.asp

 

Python String join() Method

Python String join() Method ❮ String Methods Example Join all items in a tuple into a string, using a hash character as separator: myTuple = ("John", "Peter", "Vicky") x = "#".join(myTuple) print(x) Try it Yourself » Definition and Usage The join() meth

www.w3schools.com

 

2. sorted()

: iterable한 객체의 정렬된 리스트를 리턴합니다.

 

오름차순, 내림차순을 지정할 수 있고, string은 알파벳 순, 숫자는 숫자 크기 순으로 정렬됩니다.

* string과 숫자를 모두 포함하는 객체는 정렬할 수 없습니다.

sorted(iterable_object, key=key, reverse=reverse)

 

Parameter Description
iterable_object Required. The sequence to sort, list, dictionary, tuple etc.
key Optional. A Function to execute to decide the order. Default is None
reverse Optional. A Boolean. False will sort ascending, True will sort descending. Default is False

예제1)

a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a)
print(x)


"""
실행 결과
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
"""

예제2)

a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a, reverse=True)
print(x)


"""
실행 결과
['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
"""

 

참고:www.w3schools.com/python/ref_func_sorted.asp

 

Python sorted() Function

Python sorted() Function ❮ Built-in Functions Example Sort a tuple: a = ("b", "g", "a", "d", "f", "c", "h", "e") x = sorted(a) print(x) Try it Yourself » Definition and Usage The sorted() function returns a sorted list of the specified iterable object.

www.w3schools.com

반응형