[PAI] Part2_Ch06 문자열 조작

밤초록·2021년 7월 30일
0

문자 숫자로 이루어져 있는지 판별
pg. 139

for char in s:
    # isalunum() - check alphabet or numeric
    if char.isalnum():
        strs.append(char.lower())

  • isalnum() - 문자/숫자로 이루어져 있는지 판별

  • isalpha() - 문자(영어/한글)로 이루어져 있는지 판별

  • isdigit() - 숫자로 이루어져 있는지 판별


투 포인터를 이용한 스왑
pg. 145

left, right = 0, len(s)-1
while left < right:
    # in one line, don't need to use temporary storage variable
    s[left], s[right] = s[right], s[left]
    left += 1
    right -= 1

  • 한 라인에서 두 수를 바꿔주면 임시 저장 변수 쓰지 않아도 된다

첫 번째 이후의 원소들, 첫 번째 원소 순으로 정렬
pg. 149

letters.sort(key=lambda x:(x.split()[1:], x.split()[0]))

  • sort(key=lambda x: x[1:])
    -> 첫 번째 이후의 원소들에 의해 정렬

  • sort(key=lambda x: (x[1:], x[0])
    -> 첫 번째 이후의 원소들에 의해 정렬한 후 첫 번째 원소에 의해 정렬


람다 사용하지 않고 두 번째 이후 키 정렬 후 첫 번째 키 정렬하는 함수
pg. 150

def func(x):
    return x.split()[1:], x.split()[0]
    
.
.
.

logs.sort(key=func)
print(logs)

문장 속 한글, 영어, 숫자 등만 추출
pg. 151

paragraph = "Bob 괜....찮 hit a bal ..df.df"

words = [word for word in re.sub(r'[^\w]', ' ', paragraph).split()]
print(words)
>>> ['Bob', '괜', '찮', 'hit', 'a', 'bal', 'df', 'df']

words = [word for word in re.sub(r'[^\W]', ' ', paragraph).split()]
print(words)
>>> ['....', '..', '.']
 
words = [word for word in re.sub(r'[^0-9a-zA-Z]', ' ', paragraph).split()]
print(words)
>>> ['Bob', 'hit', 'a', 'bal', 'df', 'df']



  • \w : 문자(한글/영어) 숫자 분류
  • \W : 문자(한글/영어) 숫자 아닌 것 분류

단어 count 하기
pg. 152

counts = collections.defaultdict(int)
for word in words:
    counts[word] += 1
    
print(count)
>>> {'Bob': 1, '괜': 1, '찮': 1, 'hit': 1, 'a': 1, 'bal': 1, 'df': 2}

  • defaultdict 사용해 int 기본 값, 0이 자동으로 부여되게 함

  • 키 존재 유무 확인하지 않아도 즉시 counts[word] += 1 수행 가능


가장 큰 값 추출
pg. 152

print(max(counts, key=counts.get))
>>> df

  • 딕셔너리 변수인 counts 에서 값이 가장 큰 키를 가져온다

  • 여러 가지 값이 max 값을 가져도 한 가지 값만 반환


딕셔너리 개수 처리 Counter 모듈
pg. 152

counts = collections.Counter(words)

print(counts)
>>> Counter({'df': 2, 'Bob': 1, '괜': 1, '찮': 1, 'hit': 1, 'a': 1, 'bal': 1})

print(most_common(1))
>>> [('df', 2)]

문자열 배열을 받아 애너그램 단위로 그룹핑
pg.153

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        anagrams = collections.defaultdict(list)

        for word in strs:
            anagrams[''.join(sorted(word))].append(word)

        return list(anagrams.values())

  • defaultdict(list)

  • 문자열을 sorted()를 사용해 정렬된 리스트로 변환한 후 join을 통해 문자열로 재변환
    -> 이 자체를 딕셔너리의 키 값으로 사용
    -> 값에는 문자열의 원본이 들어감


정렬 sorted
pg. 155

a = "abcd123"

print(sorted(a))
>>> ['1', '2', '3', 'a', 'b', 'c', 'd']

print(a)
>>> abcd123


c = ['ccc', 'aaaa', 'dd', 'bb']

print(sorted(c, key=len))
>>> ['dd', 'bb', 'ccc', 'aaaa']

  • sorted() 문자열도 정렬하여 리스트로 반환

  • 정렬 결과를 별도로 리턴함

  • 원본은 변하지 않음

  • key= 옵션을 지정하여 정렬을 위한 키 또는 함수를 별도로 지정할 수 있음

  • reverse=True 옵션 지정하면 역정렬 가능


정렬 sort
pg. 155

a = "abcd123"

a.sort()
'str' object has no attribute 'sort'
>>> AttributeError: 'str' object has no attribute 'sort'

b = [5, 4, 3, 9]

print(b.sort())
>>> None

print(b)
>>> [3, 4, 5, 9]

  • 문자열은 sort() 사용할 수 없음

  • 리스트 자료형이 sort() 메소드 제공하는 것

  • 제자리 정렬
    -> 입력을 출력으로 덮어 씀
    -> 별도의 추가 공간이 필요하지 않음
    -> 리턴 값이 없음

0개의 댓글