리스트란 [] 대괄호를 통해 그 값을 넣을 수 있고, 0부터 시작한다는 특징을 가진다.
코드를 통해서 이에 대한 예시를 알아보고자 한다.
mbti = ['INFP', 'ENFP', 'ESTJ', 'INTP']
print(mbti)
print(mbti[0])
>>> ['INFP', 'ENFP', 'ESTJ', 'INTP']
>>> INFP
[0]은 0번을 의미하고, 이를 출력하면 0 번째 측, 첫 번째 자리에 있는 데이터가 출력된다.
그 외에도 새로운 값을 특정 위치에 넣어 추가할 수 있다.
mbti = ['INFP', 'ENFP', 'ESTJ', 'INTP']
mbti[0] = 'infj' # 새로운 값을 넣어서 만들기
print(mbti)
print(mbti[0])
>>> ['infj', 'ENFP', 'ESTJ', 'INTP']
>>> infj
리스트에는 숫자가 올 수도, 문자열이 올 수도, 둘 다 올 수도 있다.
my_list = [123, 'apple']
print(my_list)
>>> [123, 'apple']
colors = ['red', 'blue', 'green']
대표 배열 한 개를 위와 같이 설정할 때, 이에 대해서 수정, 추가, 제거 등을 할 수 있다.
먼저 특정 위치에 수정한 사례는 아래와 같다.
colors[2] = 'black'
print(colors)
>>> ['red', 'blue', 'black']
다음으로 마지막 순서에 추가한 사례를 살펴보면,
colors.append('purple')
print(colors)
>>> ['red', 'blue', 'black', 'purple']
그 외에도 원하는 위치에 추가할 수도 있다.
colors.insert(1, 'yellow')
print(colors)
>>> ['red', 'yellow', 'blue', 'black', 'purple']
제거하는 방법으로는 두 가지가 있는데, 먼저 지워도 다시 사용할 수 없는 경우다.
del colors[0]
print(colors)
>>> ['yellow', 'blue', 'black', 'purple']
또다른 제거 방법으로 다시 반환하는 경우다.
colors.pop(0)
print(colors)
>>> ['blue', 'black', 'purple']
이것의 특징은 바로 삭제하는 것이 아니라, 반환이 가능하다는 점으로, 아래를 통해서 자세히 살펴볼 수 있다.
color = colors.pop(0)
print(colors)
print(color)
>>> ['black', 'purple']
>>> 'blue'
그 외에 제거할 때, 특정 데이터 자체를 입력해 제거하는 방법이 있다.
colors.remove('black')
print(colors)
>>> ['purple']
colors = ['blue', 'red', 'gray', 'black', 'yellow', 'orange']
colors 리스트가 위와 같을 때, 다양한 방법으로 정렬하고, 길이-갯수를 측정할 수 있다.
정렬하는 방법으로 여러가지가 있다.
# 정렬 - 원본데이터 변경
colors.sort()
print(colors)
>>> ['black', 'blue', 'gray', 'orange', 'red', 'yellow']
sort를 이용하되, 역순으로 정렬할 수 있다.
# 역순정렬
colors.sort(reverse=True)
print(colors)
>>> ['yellow', 'red', 'orange', 'gray', 'blue', 'black']
전열 결과를 다음과 같이 표현해 출려할 수 있다.
# 정렬 2
sorted(colors) # 최초의 초기화 데이터 를 변형시키지 않음.
print(colors)
print(sorted(colors))
>>> ['yellow', 'red', 'orange', 'gray', 'blue', 'black']
>>> ['black', 'blue', 'gray', 'orange', 'red', 'yellow']
요소의 갯수 또한 출력할 수 있다.
# 길이 - 요소의 갯수
print(len(colors))
print(colors[7])
print(colors[-1]) # 마지막 원소를 출력하고 싶다면
>>> 6
>>> black
>>> black
colors = ['blue', 'red', 'gray', 'black', 'yellow', 'orange']
colors 리스트가 위와 같을 때, 원하는 부분만 출력할 수 있다.
print(colors[1:5])
print(colors[:5])
print(colors[0:])
print(colors[:]) # 전체를 의미한다.
print(colors[-1:])
>>> ['red', 'orange', 'gray', 'blue']
>>> ['yellow', 'red', 'orange', 'gray', 'blue']
>>> ['yellow', 'red', 'orange', 'gray', 'blue', 'black']
>>> ['yellow', 'red', 'orange', 'gray', 'blue', 'black']
>>> ['black']
또한 리스트 전체를 새로운 변수에 넣어 표현할 수 있다.
colors_2 = colors[:]
print(colors_2)
>>> ['yellow', 'red', 'orange', 'gray', 'blue', 'black']
이러한 구조가 colors_2 = color 와 다른 것은, 최초의 할당 메모리가 동일하다는 것이다.
후자는 최초와 분리되어서 출력되지 않는다.
때문에 colors_2를 변형하면, color 또한 변형된다.
scores = [88, 100, 96, 43, 65, 78]
scores를 위와 같은 리스트라 가정하자.
이를 for 문을 통해서 리스트 내 랜덤 데이터를 뽑아 원하는 조건만족 여부에 따른 출력값도 아래와 같이 확인할 수 있다.
아래의 경우 조건은 리스트 내 임의의 값이 80 이상인지의 여부이다.
scores.sort(reverse=True)
print(scores)
for score in scores:
if score >= 80:
print(scores)
else:
print("fail")
>>> [100, 96, 88, 78, 65, 43]
>>> [100, 96, 88, 78, 65, 43]
>>> [100, 96, 88, 78, 65, 43]
>>> [100, 96, 88, 78, 65, 43]
>>> fail
>>> fail
>>> fail
scores = [88, 100, 96, 43, 65, 78]
scores를 위와 같은 리스트라 가정하자.
이 때 최댓값은 아래와 같은 코드로 알 수 있다.
max_val = max(scores)
최솟값은 아래와 같다.
min_val = min(scores)
리스트 내 총 합을 구하는 코드는 아래와 같다.
sum_val = sum(scores)
sum_values = 0
for score in scores:
sum_values = 0
for score in scores:
sum_values = sum_values + score
print(sum_values) # 합을 구하기
>>> 470
평균 또한 구할 수 있는데, 위의 코드에서 구한 합을 갯수로 나누면 된다.
avg_val = sum(scores) / len(scores)
print(avg_val)
>>> 78.333333333
튜플과 리스트는 유사해 보이지만, 튜플은 각각의 요소를 변경할 수 없다는 리스트와의 차이점을 가진다.
tup = (1, 20, 40)
임의의 튜플을 위와 같이 설정할때, 출력하면 다음과 같다.
print(tup)
>>> (100, 20, 200)
특정한 값을 재할당하면 오류가 발생한다.
tup[0] =100 # 오류
위의 코드가 그 예시이다.
하지만 전체를 새로 정의해 바꾸면 괜찮다.
tup = (100, 20, 200)
print(tup)
>>> (100, 20, 200)
tup = (1, 20, 40)
tup을 위와 같이 선언할 때,
for문을 통해서 이를 출력할 수 있다.
for x in tup:
print(x) # 순서대로 출려된다.
>>> 1
20
40
튜플을 리스트로 변환할 수 있다.
list_1 = list(tup)
print(list_1)
#리스트로 변환 2
list_2 = [x for x in tup]
print(list_2)
#리스트 변환 3
list_3=[]
for x in tup:
list_3.append(x)
print(list_3)
>>> [1, 20, 40]
>>> [1, 20, 40]
>>> [1, 20, 40]
아래와 같이 딕셔너리를 선언할 수 있다. 이는 key값과 value값으로 구분되어있다.
student = {
"student_no": "20230401",
"major": "English",
"grade": 1
}
print(student["student_no"])
>>> 20230401
딕셔너리 내 데이터 수정은 다음과 같다.
student["student_no"] = "20230101"
print(student)
print(student["student_no"])
>>> {'student_no': '20230101', 'major': 'English', 'grade': 1}
>>> 20230101
student = {
"student_no": "20230401",
"major": "English",
"grade": 1
}
위와 같이 딕셔너리를 선언할 때,
추가는 다음과 같다.
student["gpa"] = 4.5
print(student)
>>> {'student_no': '20230101', 'major': 'English', 'grade': 1, 'gpa': 4.5}
수정은 다음과 같다.
student["gpa"] = 4.3
print(student)
>>> {'student_no': '20230101', 'major': 'English', 'grade': 1, 'gpa': 4.3}
삭제는 다음과 같다.
del student["gpa"]
print(student)
>>> {'student_no': '20230101', 'major': 'English', 'grade': 1}
student = {
"student_no": "20230401",
"major": "English",
"grade": 1
}
위와 같이 딕셔너리를 선언할 때,
데이터에 접근하는 방법은 아래와 같다.
print(student.get("grade"))
>>> 1
만약 없는 데이터에 접근한다면 이와 같은 결과가 나온다.
print(student.get("gpa"))
>>> None
만약 데이터가 없을 경우 출력할 문구가 있다면, 이와 같이 입력한다.
print(student.get("gpa", "해당 키-값이 없습니다~"))
>>> 해당 키-값이 없습니다~
딕셔너리의 키를 반환하고 싶다면,
print(student.keys())
>>>dict_keys(['student_no', 'major', 'grade'])
딕셔너리의 키를 리스트로 반환한다면,
print(list(student.keys()))
>>> ['student_no', 'major', 'grade']
딕서녀리의 값을 반환한다면,
print(student.values())
>>> dict_values(['20230101', 'English', 1])
tech = {
"HTML" : "Advanced",
"JavaScript": "Intermediate",
"Python": "Expert",
"Go": "Novice"
}
임의의 딕셔너리 tech를 위와 같이 선언할 때,
key와 value 를 함께 짝지어 출력하면 다음과 같다.
for key, value in tech.items():
print(f'{key} - {value}')
>>> HTML - Advanced
JavaScript - Intermediate
Python - Expert
Go - Novice
key값만 출력하고 싶다면,
for i in tech:
print(i)
>>> HTML
JavaScript
Python
Go
value만 출력하고 싶다면,
for value in tech.values():
print(value)
>>> Advanced
Intermediate
Expert
Novice
딕셔너리 두 개를 다음과 같이 선언한다.
student_1 ={
"student_no": "1",
"gpa": "4.3"
}
student_2 ={
"student_no": "2",
"gpa": "3.8"
}
그리고 하나의 변수에 두개의 딕셔너리를 리스트로 담는다.
students = [student_1, student_2]
반복문을 통해서 두 개의 리스트에 해당하는 특정 정보를 가져오면 다음과 같다.
for student_ in students:
print(student_['student_no'])
>>> 1
2
for student_ in students:
student['graduated'] = False
print(student_)
>>> {'student_no': '1', 'gpa': '4.3'}
{'student_no': '2', 'gpa': '3.8'}
또다른 딕셔너리 student_a를 아래와 같이 정의한다
student_a = {
"subjects": ["회계원리", "중국어회화"]
}
프린트를 통해서 만든 딕셔너리를 불러오면 아래와 같이 출력된다.
print(student_a["subjects"])
>>> ['회계원리', '중국어회화']
이를 불러와 특정 정보를 출력하면 아래와 같다.
subjects_list = student_a["subjects"]
for subject in subjects_list:
print(subject)
>>> 회계원리
중국어회화
다른 딕셔너리 student_b를 아래와 같이 정의한다.
studnet_b = {
"scholarship": {
"name": "국가장학금",
"amount": "1000000"
}
}
그 정보를 출력하면 아래와 같다.
print(studnet_b)
>>>{'scholarship': {'name': '국가장학금', 'amount': '1000000'}}
이에 대해서 키 값만 출력하거나, value만 출력하거나. value를 출력하면 아래와 같다.
for key in studnet_b.keys():
print(key)
for value in studnet_b.values():
for value_2 in value.values():
print(value_2)
>>> scholarship
>>> 국가장학금
>>> 1000000
더 다양한 강의노트 및 강좌 후기 👉🏻 https://blog.naver.com/jimin201396