했던것들/PY4E(모두를 위한 파이썬)
(파이썬) 리스트 활용 (몇가지 내장함수)
2DC
2022. 5. 28. 13:32
https://docs.python.org/3/tutorial/datastructures.html
5. Data Structures — Python 3.10.4 documentation
5. Data Structures This chapter describes some things you’ve learned about already in more detail, and adds some new things as well. 5.1. More on Lists The list data type has some more methods. Here are all of the methods of list objects: list.append(x)
docs.python.org
리스트 내장함수는 위의 사이트에서 더욱 잘 설명해주고 있다.
리스트 병합
리스트 타입도 + 연산자를 활용하여 서로 다른 리스트를 더할 수 있다.
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
# [1, 2, 3, 4, 5, 6]로 출력된다.
리스트 슬라이싱
리스트도 문자열과 같이 : (콜론)을 이용해 잘라낼 수 있다.
문자열과 마찬가지로 마지막 인덱스는 본인이 포함되지 않고 -1이 되어 산출된다.
t = [9, 41, 12, 3, 74, 15]
print(t[1:3])
print(t[:4])
print(t[3:])
print(t[:])
# [41, 12]
# [9, 41, 12, 3]
# [3, 74, 15]
# [9, 41, 12, 3, 74, 15]
리스트 만들기
리스트는
변수 = list()
또는
변수 = [ 리스트1, 리스트2, 리스트3 ] 과 같은 방법으로 만들 수 있고,
.append() 메서드를 통해 리스트의 끝에 요소를 추가해줄 수 있다.
friends = list()
friends.append('Joseph')
friends.append('Glenn')
friends.append('Sally')
print(friends)
# ['Joseph', 'Glenn', 'Sally']
또한
.sort() 함수를 통해
리스트 내부를 정렬할 수 있다.
friends = list()
friends.append('Joseph')
friends.append('Glenn')
friends.append('Sally')
print(friends)
# ['Joseph', 'Glenn', 'Sally']
friends.sort()
print(friends)
# ['Glenn', 'Joseph', 'Sally']
정렬 기준은 알파벳 내림차순, 오름차순 등이 있다.
여기서는 오름차순이 적용되었다.