(Python) 내장함수: reversed, sorted, hash, callable, bool

Kepler·2020년 2월 16일
0

1. reversed():

  • 결과 : 역 iterator를 돌려준다.
  • 형식 :
reversed(seq)

# seq: 역으로 돌려줄 시퀀스 객체
  • 예제 :
# for string
seq_string = 'Python'
print(list(reversed(seq_string)))
>>>['n', 'o', 'h', 't', 'y', 'P']

# for tuple
seq_tuple = ('P', 'y', 't', 'h', 'o', 'n')
print(list(reversed(seq_tuple)))
>>>['n', 'o', 'h', 't', 'y', 'P']

# for range
seq_range = range(5, 9)
print(list(reversed(seq_range)))
>>>[8, 7, 6, 5]

# for list
seq_list = [1, 2, 4, 3, 5]
print(list(reversed(seq_list)))
>>>> [5, 3, 4, 2, 1]

커스텀 메소드 using reversed : __reversed__(self)

class Vowels:
    vowels = ['a', 'e', 'i', 'o', 'u']
    def __reversed__(self):
        return reversed(self.vowels)
v = Vowels()
print(list(reversed(v)))

>>>['u', 'o', 'i', 'e', 'a']

참고: string 객체로 리턴하기 위해서는, 다음의 방법을 사용 가능.

  • slicing
str="Python" 
stringlength=len(str) 
slicedString=str[::-1] # slicing 
print (slicedString) 
>>>nohtyP
  • join
str = 'Python' #
reversed=''.join(reversed(str)) # .join() method merges all of the characters resulting from the reversed iteration into a new string
print(reversed)
>>>nohtyP

(Content: https://www.educative.io/edpresso/how-do-you-reverse-a-string-in-python)


2. sorted()

  • 결과 : iterable 의 항목들로 새 정렬된 list를 돌려줌.
  • 형식 :
sorted(iterable, key=None, reverse=False)

# iterable : iterable한 객체
# key : key=len을 사용하여 길이순으로 정렬 가능, 또한 key= 람다식 표현으로 함수를 지정 가능ㄷ
# reverse : 역으로 반환
  • 예제 :
# vowels list
py_list = ['e', 'a', 'u', 'o', 'i']
print(sorted(py_list))
>>> ['a', 'e', 'i', 'o', 'u']

# string 
py_string = 'Python'
print(sorted(py_string))
>>> ['P', 'h', 'n', 'o', 't', 'y']

#lambda
a = sorted(a, key=lambda x: x.modified, reverse=True)

3. hash()

  • 결과 : 객체의 해시값(정수)을 돌려줌. 해시란 어떠한 값을 식별할 수 있는 정해진 길이의 정수이다. 모든 값은 고유의 해시를 가지고 있으므로, 다른 변수에 담겨있으도 값이 같으면 해시도 같다.
>>> hash("Look at me!")
4343814758193556824
>>> f = "Look at me!"
>>> hash(f)
4343814758193556824
  • 형식 :
hash(object)

# object : 해시 값을 돌려받을 객체 (정수, 문자열, float)
  • 예제 :
# hash for integer unchanged
print(hash(181))
>>> 181

# hash for decimal
print(hash(181.23))
>>> 530343892119126197

# hash for string
print(hash('Python'))
>>> 2230730083538390373

4. callable()

  • 결과 : 객체가 callable인지 아닌지를 boolean 값으로 리턴. False일 경우, 호출이 불가능하며, True의 경우에도 불가능한 경우가 있다.
  • 형식 :
callable(object)

# object : 테스트할 객체
  • 예제 :
x = 5

print(callable(x))
>>> False

def testFunc():
    print("TEST")

y = testFunc
print(callable(y))
>>> True

클래스는 호출을 통해 인스턴스를 생성하기 때문에 callable이며, 생성된 인스턴스는__call__()이 클래스 내에 정의되어 있어야 callable이다.

class Sample:
    def __call__(self):
        print('sample')

callable(Sample)
>>> True

(Example : https://technote.kr/258 [TechNote.kr])

5. bool()

  • 결과 : 값을 True of False로 바꾸어 준다.

  • 형식 :

bool([value])
  • 다음의 값들은 항상 False를 리턴한다

    • None

    • False

    • 0, 0.0, 0j (0 of any type)

    • (), [], '' (empty sequence)

    • {}

  • 예제 :
test = []
print(test,'is',bool(test))
>>> [] is False


test = [0]
print(test,'is',bool(test))
>>> [0] is True

test = 'Easy string'
print(test,'is',bool(test))
>>> Easy string is True
profile
🔰

0개의 댓글