카테고리 없음

List 자료형

멍주다배 2024. 11. 26.

collection data types_List 

컬렉션 자료형(Collection Data Types)

더보기

여러 개의 데이터를 하나의 변수에 그룹화하여 저장하고 효율적으로 관리하는 데 사용되는 자료형입니다.

일반적으로 리스트, 튜플, 딕셔너리, 세트가 있습니다.

2024.11.26 - [분류 전체보기] - Dictionary 자료형

 

Dictionary 자료형

collection data types_Dictionary컬렉션 자료형(Collection Data Types)더보기여러 개의 데이터를 하나의 변수에 그룹화하여 저장하고 효율적으로 관리하는 데 사용되는 자료형입니다.일반적으로 리스트, 튜

minjung405.tistory.com

 

 

Set 자료형

collection data types_Set 컬렉션 자료형(Collection Data Types)더보기여러 개의 데이터를 하나의 변수에 그룹화하여 저장하고 효율적으로 관리하는 데 사용되는 자료형입니다.일반적으로 리스트, 튜플,

minjung405.tistory.com

 

리스트(list)

여러 개의 항목을 순서대로 저장할 수 있는 가변 자료형 입니다.

파이썬에서 대괄호([])로 표현하며, 각 요소는 쉼표(,)로 구분하여 저장됩니다.

순서가 중요할 때 사용하고 중복된 요소를 허용하며, 인덱스를 통해 요소에 접근할 수 있습니다.

사용 예시: 학생들의 성적, 과목 이름 등

  • list(): 리스트 생성
list("abcdef")
#결과: ['a', 'b', 'c', 'd', 'e', 'f']

fruits = ["apple", "banana", "cherry", "orange"]
print(fruits)
#결과: ['apple', 'banana', 'cherry', 'orange']
  • append(): 리스트에 요소 추가
fruits.append("pear")

print(fruits)
#결과: ['apple', 'banana', 'cherry', 'orange', 'pear']
  • len(리스트명): 리스트 길이 확인
print(fruits)
print(len(fruits))

#결과:
#['apple', 'banana', 'cherry', 'orange', 'pear']
#5
  • sort(): 리스트 정렬
fruits = ['cherry', 'blueberry', 'orange', 'apple', 'pear']

fruits.sort()     #알파벳 순서로 정렬
fruits
#결과: ['apple', 'blueberry', 'cherry', 'orange', 'pear']

sort_fruits = sorted(fruits)
sort_fruits
#결과: ['apple', 'blueberry', 'cherry', 'orange', 'pear']
  • 리스트 연산
#리스트 요소끼리 더하기
fruits[0] + fruits[2]
#결과: applecherry

#리스트끼리 더하기
fruits_a = ['apple', 'avocado']
fruits_b = ['banana', 'blueberry']
            
fruits_a + fruits_b
#결과: ['apple', 'avocado', 'banana', 'blueberry']

#리스트 반복하기
fruits_a*2
#결과: ['apple', 'avocado', 'apple', 'avocado']

 

리스트 인덱싱

원하는 요소 하나만 선택할 때 사용, 원하는 요소에 접근하거나 요소를 변경할 수 있습니다.

# 리스트 요소 접근
for i in range(len(fruits)):
    print(f"fruits[{i}]: {fruits[i]}")
    
#결과
#fruits[0]: apple
#fruits[1]: banana
#fruits[2]: cherry
#fruits[3]: orange
#fruits[4]: pear

# 리스트 요소 변경
print(fruits[1])
fruits[1] = "blueberry"
print(fruits[1])

print(fruits)
#결과:
#banana
#blueberry
#['apple', 'blueberry', 'cherry', 'orange', 'pear']

 

리스트 슬라이싱

범위에 있는 여러 요소 추출할 때 사용, 문자열과 마찬가지로 끝 인덱스는 포함되지 않음

 

#세번째 요소까지 출력
fruits = ['apple', 'blueberry', 'cherry', 'orange', 'pear']

fruits[:3]
#결과: ['apple', 'blueberry', 'cherry']

#마지막 요소 빼기
fruits[:-1]
#결과: ['apple', 'blueberry', 'cherry', 'orange']

#거꾸로 출력		-> reverse()함수도 있음
fruits[ : :-1]
#결과: ['pear', 'orange', 'cherry', 'blueberry', 'apple']

#간격 설정
fruits[ : :2]   #해당 요소에서 두칸 옮겨서 출력
#결과: ['apple', 'cherry', 'pear']

 

리스트 요소 삭제

  • del: 특정 위치(인덱스)의 요소를 삭제하거나, 리스트 전체를 삭제할 때 사용
fruits = ['apple', 'blueberry', 'cherry', 'orange', 'pear']

del fruits[ :2]     #두번째 요소까지 삭제
fruits
#결과: ['cherry', 'orange', 'pear']

del fruits[-1]     #마지막 요소 삭제
fruits
#결과: ['cherry', 'orange']

del my_list		# 리스트 전체 삭제
  • remove(): 리스트의 특정 요소(값) 삭제, 중복된 값이 있으면 첫 번째로 등장한 값만 삭제
fruits = ['cherry', 'blueberry', 'orange', 'apple', 'pear']

fruits.remove('cherry')
fruits
#결과:['blueberry', 'orange', 'apple', 'pear']
  • pop(): 인덱스로 요소를 삭제하면서 값 반환, 지정하지 않으면 마지막 요소 반환하고 삭제
fruits = ['blueberry', 'orange', 'apple', 'pear']

#아무것도 지정하지 않았을 경우
fruits.pop()
#결과: pear

print(fruits)
#결과: ['blueberry', 'orange', 'apple']

#인덱스를 지정한 경우
fruits.pop(1)
#결과: orange

print(fruits)
#결과: ['blueberry', 'apple']

 

List Comprehesions

 for문과 for문-if문을 사용하여 원소들을 구성

  • for문: [i for i in iterable], for문 + if문: [i for i in iterable if 조건(i)]
sent = 'apple is a fruit, also pear is a fruit'

for_sent = [i for i in sent.split()]

for_if_sent = [i for i in sent if i in 'abcde']

print(for_if_sent.count('a'))    #문장에 a가 5개

print(for_sent)
print(for_if_sent)

#결과:
#5
#['apple', 'is', 'a', 'fruit,', 'also', 'pear', 'is', 'a', 'fruit']
#['a', 'e', 'a', 'a', 'e', 'a', 'a']

중첩 리스트, 삼중 리스트

#중첩 리스트
fruits = [1, 2, 3, ['apple', 'blueberry']]

for i in fruits:
  print(i)
#결과
#1
#2
#3
#['apple', 'blueberry']

#삼중 리스트
fruits = [1, 2, ['apple', 'blueberry', ['fruit', 'is', 'good']]]
for i in fruits:
  print(i)
#결과
#1
#2
#['apple', 'blueberry', ['fruit', 'is', 'good']]

#삼중 리스트 인덱싱
fruits[2]
#결과:['apple', 'blueberry', ['fruit', 'is', 'good']]

fruits[2][2]
#결과:['fruit', 'is', 'good']
fruits[2][2][2]
#결과: good

단어 맞추기 게임

컴퓨터가 랜덤으로 영어 단어를 선택하면, 사용자는 알파벳 중 하나를 선택하여 단어를 맞춥니다.

선택한 알파벳이 단어에 있으면 성공, 틀리면 기회가 줄어듭니다.

총 9번의 기회가 있으며 게임 오버되기 전에 영어 단어를 맞추면 최종 성공입니다.

단어를 맞췄을때, 단어를 끝까지 맞추지 못했을 때

 

코드 업데이트 해보기

1. 좀 더 간단하게 코드를 짜보기

2. 중복된 단어를 입력했을 때 기회를 차감하지 않고 알려주기

3. 전체 알파벳 중에 사용한 알파벳 보여주기

4. 빈칸을 제출했을 때 잘못 눌렀다고 다시 알려주기