파이썬 자료구조 code

파이썬에서 데이터를 다루는데 필요한 코드들 정리하였습니다.

1. list

# 리스트 생성
fruits = ["apple", "banana", "cherry"]
print("Original list:", fruits)

# 리스트 끝에 요소 추가
fruits.append("orange")
print("List after appending:", fruits)

# 특정 위치에 요소 삽입
fruits.insert(1, "mango")
print("List after inserting:", fruits)

# 요소 제거
fruits.remove("banana")
print("List after removing an element:", fruits)

# 인덱스를 통해 요소 접근
print("Element at index 2:", fruits[2])

# 리스트 슬라이싱
print("Sliced list (first 3 elements):", fruits[:3])

# 리스트 길이
print("Length of the list:", len(fruits))

# 리스트를 반복문으로 순회
print("Fruits in the list:")
for fruit in fruits:
    print(fruit)

# 리스트에 특정 요소가 있는지 확인
if "apple" in fruits:
    print("Apple is in the fruits list")
else:
    print("Apple is not in the fruits list")

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

# 리스트 반전
fruits.reverse()
print("Reversed list:", fruits)

2. tuple

# 튜플 생성
coordinates = (10, 20, 30)
print("Original tuple:", coordinates)

# 튜플 요소 접근
print("First element:", coordinates[0])
print("Last element:", coordinates[-1])

# 튜플 길이
print("Length of the tuple:", len(coordinates))

# 튜플을 반복문으로 순회
print("Coordinates:")
for coord in coordinates:
    print(coord)

# 튜플에 특정 요소가 있는지 확인
if 20 in coordinates:
    print("20 is in the coordinates")
else:
    print("20 is not in the coordinates")

# 튜플 언패킹
x, y, z = coordinates
print(f"Unpacked: x = {x}, y = {y}, z = {z}")

# 튜플 연결
more_coords = (40, 50)
combined_coords = coordinates + more_coords
print("Combined tuple:", combined_coords)

# 튜플 슬라이싱
print("Sliced tuple (first 2 elements):", coordinates[:2])

# 튜플의 불변성
try:
    coordinates[0] = 100
except TypeError as e:
    print("Error:", e)

3. 집합

# 집합 생성
fruits = {"apple", "banana", "cherry"}
print("Original set:", fruits)

# 집합에 요소 추가
fruits.add("orange")
print("Set after adding an element:", fruits)

# 집합에서 요소 제거
fruits.remove("banana")
print("Set after removing an element:", fruits)

# 집합에 특정 요소가 있는지 확인
if "apple" in fruits:
    print("Apple is in the set")
else:
    print("Apple is not in the set")

# 집합 길이
print("Length of the set:", len(fruits))

# 집합을 반복문으로 순회
print("Fruits in the set:")
for fruit in fruits:
    print(fruit)

# 집합 합집합
other_fruits = {"pineapple", "mango", "papaya"}
all_fruits = fruits.union(other_fruits)
print("Union of sets:", all_fruits)

# 집합 교집합
common_fruits = fruits.intersection(other_fruits)
print("Intersection of sets:", common_fruits)

# 집합 차집합
unique_fruits = fruits.difference(other_fruits)
print("Difference of sets:", unique_fruits)

# 집합 대칭 차집합
symmetric_difference = fruits.symmetric_difference(other_fruits)
print("Symmetric difference of sets:", symmetric_difference)

4. dictionary

# 딕셔너리 생성
person = {"name": "Alice", "age": 30, "city": "New York"}
print("Original dictionary:", person)

# 딕셔너리 값 접근
print("Name:", person["name"])
print("Age:", person["age"])

# 새로운 키-값 쌍 추가
person["email"] = "alice@example.com"
print("Dictionary after adding a new key-value pair:", person)

# 값 업데이트
person["age"] = 31
print("Dictionary after updating age:", person)

# 키-값 쌍 제거
del person["city"]
print("Dictionary after removing a key-value pair:", person)

# 딕셔너리의 키를 반복문으로 순회
print("Keys in the dictionary:")
for key in person:
    print(key)

# 딕셔너리의 값 반복문으로 순회
print("Values in the dictionary:")
for value in person.values():
    print(value)

# 딕셔너리의 키-값 쌍을 반복문으로 순회
print("Key-value pairs in the dictionary:")
for key, value in person.items():
    print(f"{key}: {value}")

# 딕셔너리에 특정 키가 있는지 확인
if "name" in person:
    print("Name is in the dictionary")
else:
    print("Name is not in the dictionary")

# 딕셔너리 길이
print("Length of the dictionary:", len(person))

 
필요하신 코드 복사하셔서 사용하시기 바랍니다.

파이썬 문법 기초 정리
파이썬 기본 문법 code
파이썬 자료구조 code
파이썬 라이브러리 code
파이썬 flask를 이용한 홈페이지
이름으로 성별,나이,나라 판단하는 Open API 파이썬 예제

Leave a Comment