개인 공부 설명 모음

Python 리스트, 튜플, 딕셔너리, 집합 등 기본 자료구조 실습

상상모음 2024. 11. 17. 17:49

리스트 (List)

리스트는 변경 가능한 순서가 있는 컬렉션이다.

# 리스트 생성
fruits = ["apple", "banana", "cherry"]

# 요소 접근
print("첫 번째 과일:", fruits[0])

# 요소 추가
fruits.append("orange")
print("추가 후 리스트:", fruits)

# 요소 삭제
fruits.remove("banana")
print("삭제 후 리스트:", fruits)

# 리스트 길이
print("리스트 길이:", len(fruits))

# 리스트 정렬
fruits.sort()
print("정렬된 리스트:", fruits)

튜플 (Tuple)

튜플은 변경 불가능한 순서가 있는 컬렉션이다.

# 튜플 생성
numbers = (1, 2, 3, 4)

# 요소 접근
print("첫 번째 숫자:", numbers[0])

# 길이 확인
print("튜플 길이:", len(numbers))

# 튜플 언패킹
a, b, c, d = numbers
print("언패킹된 값:", a, b, c, d)

# 튜플은 변경 불가
# numbers[0] = 10  # 오류 발생 (튜플은 수정 불가능)

 


 

딕셔너리 (Dictionary)

딕셔너리는 키-값 쌍으로 이루어진 변경 가능한 자료구조이다.

 

# 딕셔너리 생성
person = {"name": "Alice", "age": 25, "city": "Seoul"}

# 값 접근
print("이름:", person["name"])
print("도시:", person.get("city"))

# 값 추가 및 수정
person["age"] = 30
person["job"] = "developer"
print("수정 후 딕셔너리:", person)

# 키-값 쌍 삭제
del person["city"]
print("삭제 후 딕셔너리:", person)

# 딕셔너리 반복
for key, value in person.items():
    print(f"{key}: {value}")

 


집합 (Set)

집합은 중복되지 않은 요소를 가진 변경 가능한 자료구조이다.

 

# 집합 생성
numbers = {1, 2, 3, 4, 5}

# 요소 추가
numbers.add(6)
print("추가 후 집합:", numbers)

# 요소 삭제
numbers.discard(2)
print("삭제 후 집합:", numbers)

# 집합 연산
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print("합집합:", set_a | set_b)  # set_a.union(set_b)
print("교집합:", set_a & set_b)  # set_a.intersection(set_b)
print("차집합:", set_a - set_b)  # set_a.difference(set_b)

 


 

리스트, 튜플, 딕셔너리, 집합 혼합 사용

 

# 리스트 안에 딕셔너리
students = [
    {"name": "Alice", "age": 24},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 23},
]

for student in students:
    print(f"이름: {student['name']}, 나이: {student['age']}")

# 튜플 안에 집합
tuple_with_sets = ({1, 2, 3}, {3, 4, 5})
for s in tuple_with_sets:
    print("집합 요소:", s)

# 딕셔너리 값으로 리스트
grades = {"Alice": [90, 85, 88], "Bob": [78, 80, 82]}
for name, scores in grades.items():
    print(f"{name}의 점수 평균: {sum(scores) / len(scores):.2f}")

 


 

자료구조 변환

# 리스트 -> 집합
list_data = [1, 2, 2, 3, 4]
set_data = set(list_data)
print("집합으로 변환:", set_data)

# 집합 -> 리스트
unique_list = list(set_data)
print("리스트로 변환:", unique_list)

# 튜플 -> 리스트
tuple_data = (10, 20, 30)
list_data = list(tuple_data)
print("리스트로 변환:", list_data)