Python 리스트 기본 조작 및 슬라이싱 연습

주어진 리스트를 활용하여 다양한 기본 조작과 슬라이싱 기법을 연습합니다.

리스트 기본 조작

다음 리스트를 사용하여 각 요구사항을 구현합니다.


initial_list = ["alex", "wusir", "eric", "rain", "alex"]
    
  1. 리스트 길이 계산 및 출력

    
    print(f"리스트 길이: {len(initial_list)}")
                
  2. 'seven' 요소 추가 후 리스트 출력

    
    temp_list = initial_list[:] # 원본 유지를 위해 복사
    temp_list.append('seven')
    print(f"추가 후 리스트: {temp_list}")
                
  3. 인덱스 0에 'Tony' 삽입 후 리스트 출력

    
    temp_list = initial_list[:]
    temp_list.insert(0, 'Tony')
    print(f"삽입 후 리스트: {temp_list}")
                
  4. 인덱스 1의 요소를 'Kelly'로 수정 후 리스트 출력

    
    temp_list = initial_list[:]
    if len(temp_list) > 1:
        temp_list[1] = 'Kelly'
    print(f"수정 후 리스트: {temp_list}")
                
  5. 다른 리스트의 모든 요소를 현재 리스트에 확장 (한 줄 코드, 반복문 사용 금지)

    
    list_to_extend = [1, 'a', 3, 4, 'heart']
    temp_list = initial_list[:]
    temp_list.extend(list_to_extend)
    print(f"확장 후 리스트: {temp_list}")
                
  6. 문자열의 각 문자를 현재 리스트에 확장 (한 줄 코드, 반복문 사용 금지)

    
    string_to_extend = 'qwert'
    temp_list = initial_list[:]
    temp_list.extend(string_to_extend)
    print(f"문자열 확장 후 리스트: {temp_list}")
                
  7. 'eric' 요소 삭제 후 리스트 출력

    
    temp_list = initial_list[:]
    if 'eric' in temp_list:
        temp_list.remove('eric')
    print(f"삭제 후 리스트: {temp_list}")
                
  8. 인덱스 2의 요소 삭제 및 삭제된 요소와 리스트 출력

    
    temp_list = initial_list[:]
    if len(temp_list) > 2:
        removed_element = temp_list.pop(2)
        print(f"삭제된 요소: {removed_element}")
        print(f"삭제 후 리스트: {temp_list}")
    else:
        print("삭제할 요소가 없습니다.")
                
  9. 인덱스 2부터 4 이전까지의 요소 삭제 후 리스트 출력

    
    temp_list = initial_list[:]
    if len(temp_list) > 4: # 인덱스 4까지 접근 가능해야 함
        del temp_list[2:4]
        print(f"슬라이스 삭제 후 리스트: {temp_list}")
    else:
        print("삭제할 범위의 요소가 충분하지 않습니다.")
                
  10. 리스트 모든 요소 반전 후 리스트 출력

    
    temp_list = initial_list[:]
    temp_list.reverse() # reverse()는 제자리에서 변경하며 반환값은 None
    print(f"반전 후 리스트: {temp_list}")
                
  11. 'alex' 요소의 출현 횟수 계산 및 출력

    
    count_alex = initial_list.count('alex')
    print(f"'alex'의 출현 횟수: {count_alex}")
                

리스트 슬라이싱 활용

다음 리스트를 사용하여 슬라이싱으로 새로운 리스트를 생성합니다.


source_list = [1, 3, 2, "a", 4, "b", 5, "c"]
    
  1. 슬라이싱으로 `l1 = [1, 3, 2]` 생성

    
    l1 = source_list[:3]
    print(f"l1: {l1}")
                
  2. 슬라이싱으로 `l2 = ['a', 4, 'b']` 생성

    
    l2 = source_list[3:6]
    print(f"l2: {l2}")
                
  3. 슬라이싱으로 `l3 = [1, 2, 4, 5]` 생성 (짝수 인덱스 요소)

    
    l3 = source_list[::2]
    print(f"l3: {l3}")
                
  4. 슬라이싱으로 `l4 = [3, 'a', 'b']` 생성

    
    l4 = source_list[1:6:2]
    print(f"l4: {l4}")
                
  5. 슬라이싱으로 `l5 = ['c']` 생성

    
    l5 = source_list[-1:]
    print(f"l5: {l5}")
                
  6. 슬라이싱으로 `l6 = ['b', 'a', 3]` 생성 (역순)

    
    # 원본 리스트의 일부를 선택하고 역순으로 만들기
    sub_list = source_list[1:6] # [3, 2, 'a', 4, 'b']
    l6 = sub_list[::-1] # ['b', 4, 'a', 2, 3] - 요구사항과 다름.
    # 요구사항에 맞는 슬라이싱:
    l6_correct = source_list[5::-2] # 'b'부터 시작하여 두 칸씩 건너뛰며 역순
    print(f"l6 (수정): {l6_correct}") # ['b', 'a', 3]
                

중첩 리스트 조작

다음 중첩 리스트를 사용하여 각 요구사항을 구현합니다.


nested_list = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "ab", "adv"]
    
  1. 'tt'를 대문자로 변경 (두 가지 방법)

    1. 방법 1: 인덱싱 및 `.upper()` 사용
      
      temp_nested_list = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "ab", "adv"]
      # 'tt'의 정확한 위치: temp_nested_list[3][2][1][0]
      if isinstance(temp_nested_list[3][2][1][0], str):
          temp_nested_list[3][2][1][0] = temp_nested_list[3][2][1][0].upper()
      print(f"대문자 변경 (upper): {temp_nested_list}")
                          
    2. 방법 2: `.replace()` 사용
      
      temp_nested_list_replace = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "ab", "adv"]
      if isinstance(temp_nested_list_replace[3][2][1][0], str):
          temp_nested_list_replace[3][2][1][0] = temp_nested_list_replace[3][2][1][0].replace('tt', 'TT')
      print(f"대문자 변경 (replace): {temp_nested_list_replace}")
                          
  2. 숫자 3을 문자열 '100'으로 변경 (두 가지 방법)

    1. 방법 1: 직접 인덱싱하여 값 변경
      
      temp_nested_list_num = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "ab", "adv"]
      # 첫 번째 3: temp_nested_list_num[1]
      temp_nested_list_num[1] = '100'
      # 중첩된 두 번째 3: temp_nested_list_num[3][2][1][1]
      if len(temp_nested_list_num[3][2][1]) > 1 and isinstance(temp_nested_list_num[3][2][1][1], int):
           temp_nested_list_num[3][2][1][1] = '100'
      print(f"숫자 3을 '100'으로 변경 (인덱싱): {temp_nested_list_num}")
                          
    2. 방법 2: 삽입(`insert`) 및 삭제(`pop`) 사용 (주의: 원래 구조 변경)
      
      temp_nested_list_insert = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "ab", "adv"]
      # 첫 번째 3 삭제 및 '100' 삽입
      if len(temp_nested_list_insert) > 2 and temp_nested_list_insert[1] == 3:
          temp_nested_list_insert.pop(1)
          temp_nested_list_insert.insert(1, '100')
      
      # 중첩된 두 번째 3 삭제 및 '100' 삽입
      inner_list_level3 = temp_nested_list_insert[3][2][1]
      if len(inner_list_level3) > 1 and inner_list_level3[1] == 3:
          inner_list_level3.pop(1)
          inner_list_level3.insert(1, '100')
      print(f"숫자 3을 '100'으로 변경 (삽입/삭제): {temp_nested_list_insert}")
                          
  3. 문자열 '1'을 숫자 101로 변경 (두 가지 방법)

    1. 방법 1: 직접 인덱싱하여 값 변경
      
      temp_nested_list_str = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "ab", "adv"]
      # 문자열 '1'의 위치: temp_nested_list_str[3][2][1][2]
      if len(temp_nested_list_str[3][2][1]) > 2 and temp_nested_list_str[3][2][1][2] == '1':
          temp_nested_list_str[3][2][1][2] = 101
      print(f"문자열 '1'을 101로 변경 (인덱싱): {temp_nested_list_str}")
                          
    2. 방법 2: 삽입(`insert`) 및 삭제(`pop`) 사용 (주의: 원래 구조 변경)
      
      temp_nested_list_insert_str = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "ab", "adv"]
      inner_list_level3_str = temp_nested_list_insert_str[3][2][1]
      # '1'의 위치를 찾아 삭제 후 101 삽입
      try:
          index_of_1 = inner_list_level3_str.index('1')
          inner_list_level3_str.pop(index_of_1)
          inner_list_level3_str.insert(index_of_1, 101)
          print(f"문자열 '1'을 101로 변경 (삽입/삭제): {temp_nested_list_insert_str}")
      except ValueError:
          print("문자열 '1'을 찾을 수 없습니다.")
                          

문자열 합치기

다음 리스트의 요소를 밑줄(`_`)로 연결하여 하나의 문자열로 만듭니다.


join_list = ["alex", "eric", "rain"]
result_string = "_".join(join_list)
print(f"결합된 문자열: {result_string}")
    

조건부 필터링 및 새 리스트 생성

주어진 리스트에서 특정 조건을 만족하는 요소를 찾아 새 리스트에 추가합니다.


filter_list = ["taibai ", "alexC", "AbC ", "egon", "Ritian", " Wusir", " agc"]
filtered_elements = []

for item in filter_list:
    cleaned_item = item.strip() # 공백 제거
    # 'A' 또는 'a'로 시작하고 'c'로 끝나는지 확인
    if cleaned_item.lower().startswith('a') and cleaned_item.lower().endswith('c'):
        filtered_elements.append(cleaned_item)

print(f"필터링된 요소: {filtered_elements}")
    

민감한 단어 필터링 프로그램

사용자 입력을 받아 민감한 단어를 `***`로 대체합니다.


sensitive_words = ["苍老师", "东京热", "武藤兰", "波多野结衣"]
user_input = input("댓글을 입력하세요: ")

processed_input = user_input
for word in sensitive_words:
    if word in processed_input:
        # 모든 민감 단어를 '*'로 대체 (단순화된 버전)
        # 실제로는 해당 단어 길이만큼 '*'을 생성하는 것이 좋음
        processed_input = processed_input.replace(word, '*' * len(word))

print(f"처리된 댓글: {processed_input}")
    

중첩 리스트 순회 및 요소 출력

리스트를 순회하며 중첩된 리스트의 요소까지 모두 출력합니다.


deep_list = [1, 3, 4, 'xiaom', [3, 7, 8, [5, 6, 7, 8], 'taibai'], 5, 'hotdog']

def print_list_elements(data):
    for element in data:
        if isinstance(element, list):
            print_list_elements(element) # 재귀 호출
        else:
            print(element)

print("중첩 리스트 요소 출력:")
print_list_elements(deep_list)
    

리스트의 주요 조작 메소드 요약

  • append(item): 리스트 끝에 단일 항목 추가.
  • extend(iterable): 리스트 끝에 다른 반복 가능한 객체(리스트, 튜플 등)의 모든 항목을 추가.
  • pop([index]): 지정된 인덱스의 항목을 제거하고 반환. 인덱스가 없으면 마지막 항목 제거.
  • insert(index, item): 지정된 인덱스에 항목 삽입.
  • remove(value): 리스트에서 처음으로 나타나는 특정 값 제거.
  • reverse(): 리스트의 항목 순서를 제자리에서 반대로 변경.
  • count(value): 리스트에서 특정 값이 나타나는 횟수 반환.
  • index(value, [start, [end]]): 리스트에서 특정 값의 첫 번째 인덱스 반환.
  • sort([key, [reverse]]): 리스트 항목을 제자리에서 정렬.
  • copy(): 리스트의 얕은 복사본 반환.

태그: python list Slice manipulation data structures

7월 28일 21:47에 게시됨