python 기본 문법 정리

JUNSUNG LEE·2023년 12월 28일

사용자 입력

📌input( )

a = input()
print(a)
print(type(a))

result :

3 
<class 'str'>

input은 입력되는 모든 것을 문자열로 취급하기 때문에 위 코드에 입력된 '3'숫자가 아닌 문자열이라는 것을 주의해야 함.


정렬

📌.sort( ) vs sorted( )

파이썬은 sorted( ) 함수와 list.sort( ) 메서드 두 가지 정렬 방식을 제공한다.

nums = [2, 3, 1, 5, 6, 4, 0]

print(sorted(nums))   # [0, 1, 2, 3, 4, 5, 6]
print(nums)           # [2, 3, 1, 5, 6, 4, 0]

print(nums.sort())    # None
print(nums)           # [0, 1, 2, 3, 4, 5, 6]

위 예시에서 알 수 있듯이 sorted( ) 함수는 기존 리스트는 그대로 두고 새로운 정렬된 리스트를 return 한다.
이와는 반대로 .sort( ) 메서드는 None 을 return 하고, 기존 리스트를 정렬해서 변경한다.


기본적으로 sort함수는 list 클래스의 메서드로 list객체에서만 사용할 수 있다. 그에 반해 sorted함수는 iterable 객체(list, string, tuple, dictionary 등등...)을 파라미터로 받을 수 있는 메서드이다.

📌Using key parameter

다음의 key 매개변수는 함수로 값을 전달받고, 그 함수의 조건에 따라 정렬한다.

📌sorted( )

# Syntax:
sorted(iterable, key, reverse=False)

Example

L = ['aaaa', 'bbb', 'cc', 'd']
 
# sorted without key parameter
print(sorted(L))
 
# sorted with key parameter
print(sorted(L, key=len))

Output

['aaaa', 'bbb', 'cc', 'd']
['d', 'cc', 'bbb', 'aaaa']

📌sort( )

# Syntax:
List.sort(key, reverse=False)

Example

def sortSecond(val):
    return val[1]
 
 
# list1 to demonstrate the use of sorting
# using  second key
list1 = [(1, 5), (3, 3), (2, 1)]
 
# sorts the array in ascending according to
# second element
list1.sort(key=sortSecond)
print(list1)
 
# sorts the array in descending according to
# second element
list1.sort(key=sortSecond, reverse=True)
print(list1)

Output

[(2, 1), (3, 3), (1, 5)]
[(1, 5), (3, 3), (2, 1)]

return val[1] != (3, 3)인 이유!
key를 이용하여 함수를 받을때는 함수 매개변수에 list자체를 전달해 주는것이 아닌 list의 요소들을 순차적으로 전달해줌.


sorted()sort()
The sorted() function returns a sorted list of the specific iterable object.The sort() method sorts the list. returns None.
We can specify ascending or descending order while using the sorted() functionIt sorts the list in ascending order by default.
syntax:
sorted(iterable, key=key, reverse=reverse)
syntax:
list.sort(key=myFunc, reverse=True/False)
Its return type is a sorted list.We can also use it for sorting a list in descending order.
It can only sort a list that contains only one type of value.It sorts the list in-place.



Lambda Function

lambda 함수는 여러개의 인자를 받을 수 있지만 하나의 표현식만 받을 수 있다.

# Syntax:
lambda arguments : expression -> (return 해주는 value)

Example: 10을 더해주는 함수

x = lambda a : a + 10
print(x(5))

Example: n을 곱해주는 함수

def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

Example: 두번째 인자를 기준으로 정렬후, 두번째 인자가 같을시 첫번째 인자를 기준으로 정렬

data = [(1, 'b'), (2, 'a'), (3, 'c')]
data.sort(key=lambda x: (x[1], x[0]))

참조
https://www.geeksforgeeks.org/python-difference-between-sorted-and-sort/

https://gongmeda.tistory.com/13

profile
backend developer

0개의 댓글