[Python] class가 원소인 배열 데이터 처리
·
✏️ Study/🐍 Python
📍로그인, 로그아웃 이력으로 현재 로그인된 유저 파악하기- 데이터 구조class Event: def __init__(self, event_date, event_type, machine_name, user): self.date = event_date # 시간 self.type = event_type # 로그인 or 로그아웃 self.machine = machine_name # 접속 서버 self.user = user # 유저 - 데이터 예시events = [ Event("2023-01-02 11:38:03", "logout", "webserver.local", "jordan"), Event("2023-01-02 10:19:31", "log..
[Python] 정렬(sort, sorted) 차이
·
✏️ Study/🐍 Python
📍sort- 원본 배열을 변형numbers = [4, 6, 1, 67, 23]print(numbers) # [4, 6, 1, 67, 23]numbers.sort()print(numbers) # [1, 4, 6, 23, 67]numbers.sort(reverse=True)print(numbers) # [67, 23, 6, 4, 1] 📍sorted- 원본 배열을 변형하지 않음numbers = [4, 6, 1, 67, 23]print(sorted(numbers)) # [1, 4, 6, 23, 67]print(numbers) # [4, 6, 1, 67, 23] -> 원본이 바뀌지 않음print(sorted(numbers, reverse=True)) # [67, 23, 6, 4, 1]print(nu..
[Python] divmod로 몫과 나머지를 한번에 구하기
·
✏️ Study/🐍 Python
📍참고https://www.acmicpc.net/problem/2720 2720번: 세탁소 사장 동혁각 테스트케이스에 대해 필요한 쿼터의 개수, 다임의 개수, 니켈의 개수, 페니의 개수를 공백으로 구분하여 출력한다.www.acmicpc.net 매우 익숙한 그리디 문제.divmod 메서드를 사용하면 // 와 % 연산자를 함께 사용할 때 유용하다 📍코드N = int(input())data = [int(input()) for i in range(N)]coins = [25, 10, 5, 1]for C in data: rest = C answer = [] for coin in coins: # divmod(x, y) : x를 y로 나눈 몫과 나머지를 tuple로 반환할 수 있다 ..
[Python] Module
·
✏️ Study/🐍 Python
파이썬 표준 라이브러리 사용해보기📍randomimport randomrandom.randint(1, 10) # 1 ~ 10 에서 랜덤한 정수 1개 리턴 (10도 포함됨) 📍datetimeimport datetime# 현재 시간now = datetime.datetime.now()print(now) # datetime 클래스의 __str__ 에 적용되어 있음print(now.year) # 현재 연도# deltatime은 시간끼리 연산에 사용 가능print(datetime.timedelta(days=31)) # 31 days, 0:00:00
[Python] Class 상속
·
✏️ Study/🐍 Python
📍클래스 상속- 상속받는 클래스를 서브 클래스라고 한다.- 서브 클래스는 부모 클래스의 프로퍼티와 메서드를 받아오며, 서브 클래스에서 이를 따로 정의할 수 있다- 클래스 상속으로 코드 중복을 줄일 수 있다 class Animal: sound = "" def __init__(self, name): self.name = name def speak(self): print("{sound} I'm {name} {sound}".format(name=self.name, sound=self.sound))# 서브 클래스 1class Piglet(Animal): sound = "Oink!" # 프로퍼티 오버라이딩# 서브 클래스 2class Cow(Animal): sou..
[Python] Class, 특수 메서드, Docstring
·
✏️ Study/🐍 Python
📍클래스 및 메서드 정의class ClassName: def method_name(self, other_parameters): body_of_method - 메서드의 첫 번째 매개변수(self)는 현재 인스턴스를 나타낸다- self 예시class Dog: years = 0 def dog_years(self): return self.years * 7fido = Dog()fido.years = 3print(fido.dog_years()) # 21 - 클래스 예시 1class Person: apples = 0 ideas = 0johanna = Person()johanna.apples = 1johanna.ideas = 1martin = Person()mart..
[Python] dir, help 메서드 +a
·
✏️ Study/🐍 Python
📍dirdir(인스턴스) : 해당 인스턴스의 클래스가 갖는 프로퍼티와 메서드를 모두 반환 예시 - 문자열 클래스의 모든 프로퍼티와 메서드 반환print(type("")) # print(dir(""))# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',# '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',# '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',# '__mod__', '__mul_..
[Python] Dictionary 연산, 메서드
·
✏️ Study/🐍 Python
1️⃣연산len(dictionary)for key in dictionary : 딕셔너리의 각 키를 순회 가능for key, value in dictionary : 딕셔너리의 각 키와 밸류를 순회 가능if key in dictionarydel dictionary[key] : 해당 필드 제거 2️⃣메서드dict.get(key, default) : 키에 해당하는 요소를 반환하거나 존재하지 않는 경우, 기본값을 반환dict.keys() : 키 시퀀스를 반환dict.values() : 값 시퀀스를 반환dict.items() : (키, 값) 형태의 튜플들의 시퀀스를 반환dict.update(other_dict) : concat처럼 다른 딕셔너리 필드를 추가 (형태가 같아야 함) 3️⃣예시- 딕셔너리 순회 + 튜플 ..