[Python] 내가 사용했던 어려운 문법들

MiMi·2022년 4월 20일
0

📚Python

목록 보기
2/2
post-thumbnail

Python으로 코딩할 때 내가 사용했었지만 까먹을 것 같은 문법들을 전부 정리해보려한다.
이름하여.. MM 만의 Python 사전!!

enumerate

배열의 인덱스와 원소를 동시에 접근할 수 있다.

for i, letter in enumerate(['A', 'B', 'C']):
     print(i, letter)
# 출력 결과
0 A
1 B
2 C

시작 인덱스 변경

for i, letter in enumerate(['A', 'B', 'C'], start=1): #1부터 시작

ast 라이브러리

ast.literal_eval()

변수가 string 타입으로 '[사과, 바나나, 딸기]' 이런식으로 되어있을 때 리스트 타입인 [사과, 바나나, 딸기]로 반환해준다.
객체도 마찬가지다.

import ast
list_in_str = '[1, 2, 3, 4, 5]'
list_data = ast.literal_eval(list_in_str)
print(type(list_data)) #list - correct solution

list_in_str2 = "{'a': 1, 'b': 2, 'c': 3}"
list_data2 = ast.literal_eval(list_in_str2)
print(type(list_data2)) #dict

sum과 zip

x = [1, 2, 3, 4, 5]
w = [1, 2, 3, 4, 5]
output = sum([x+i * w_i for x_i, w_i in zip(x,w)])

=> x와 w의 원소를 각각 곱한 값의 합이 output이다.

리스트 만들기

arr = [1] * n #길이 n의 리스트가 만들어진다.
arr = [int(input()) for _ in range(n)] #n번만큼 입력을 받고, 입력값을 원소로 가진 리스트가 만들어진다.
arr2 = [list(map(int, input().split())) for _ in range(n)] #n행의 2차원 배열이 만들어진다.

정렬

arr.sort() #사전 순 정렬
arr.sort(key = len) #길이 순 정렬

문자열 뒤집기

str = "hi"
str[::-1] # "ih"

최빈값 찾기

from collections import Counter
numbers = [1, 2, 3, 3, 4, 4, 4, 5, 5]
cnt = Counter(numbers)
cnt.most_common() #매개변수 넣어주면 상위 n개의 결과
#[(4, 3), (3, 2), (5, 2), (1, 1), (2, 1)] 첫 번째 요소는 값, 두 번째 요소는 횟수

# 최빈값 찾기
def modefinder(numbers):   #numbers는 리스트나 튜플 형태의 데이터
    c = Counter(numbers)
    mode = c.most_common(1)
    return mode[0][0]
# 2개 이상
def modefinder(numbers):
    c = Counter(numbers)
    order = c.most_common()
    maximum = order[0][1]

    modes = []
    for num in order:
        if num[1] == maximum:
            modes.append(num[0])
    return modes #최빈값들이 들어있는 리스트 반환

빠른 입출력

import sys
input = sys.stdin.readline
print = sys.stdout.write

유니코드 반환

ord('a') #97
ord('가') #44032

주의할 점

input()은 개행문자 "\n"까지 읽어들이기 때문에 .rstrip()등으로 지워야한다.

import sys
input = sys.stdin.readline

n = input()              #"1"을 입력 할 때,

print(list(n))           #['1', '\n']
print([int(n)])          #[1]
print(list(n.rstrip()))  #['1']

print()는 출력 방식이 다음과 같이 바뀌어 버린다.

print = sys.stdout.write

print("%s\n" % "123")  #123
print("%s\n" % ("12" + "3"))  #123
print("%d + %d = %d\n" % (1, 2, 1 + 2))  #1 + 2 = 3

참고문헌

profile
이제 막 입문한 코린이 -> 이전중 https://mimi98.tistory.com/

0개의 댓글