2 minute read

Newly Learned

replace() 반복 사용

파이썬 문법 중에는 특정 문자를 지정한 문자로 바꾸는 replace()라는 함수가 있다. str type의 내장함수이며 여러 문자를 지우고 싶을 때는 다음과 같이 .replace를 반복한 구문으로 쓰면 편하다.

1
2
3
4
def remove_special_characters(text):
    processed_text = []
    for lines in text:
        processed_text.append(lines.replace("'",'').replace("!",'').replace(',',''))


Filtered list using for & if

for와 if문을 같이 사용해서 특정 list 자료형으로 부터 원하는 조건을 만족하는 list를 뽑아내는 코드를 간결하게 작성할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
words = [
    'apple',
    'banana',
    'alpha',
    'bravo',
    'cherry',
    'charlie',
]

def filter_by_prefix(words, prefix):
    return [word for word in words if word.startswith(prefix)]

a_words = filter_by_prefix(words, 'a')
print(a_words)

실행 결과는 아래와 같다.


n중 비교 sorted()

아래처럼 여러 tuple을 element로 가지고 있는 list 자료형에 대해서 첫 번째 원소에 대해서만 오름차순 정렬을 한다면 key 값에 return 값이 하나인 lambda 함수를 넣으면 되지만, 같은 순위일 때 다음 원소에 대해 오름차순 정렬을 하고 싶다면 key 값에 return 값이 tuple 형태인 lambda 함수를 작성하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
pairs = [
    ('a', 8, 'c'),
    ('a', 4, 'b'),
    ('a', 15, 'd'),
    ('b', 4, 'a'),
    ('b', 1, 'f')
]

# 첫 번째 element만 비교한 sorted
print(sorted(pairs, key = lambda x: x[0], reverse=False))

# 3중 비교 sorted
print(sorted(pairs, key=lambda x: (x[0], x[1], x[2]), reverse=False))

결과는 아래 그림과 같게 된다.

Leave a comment