Python/기초
파이썬 기초⑤ 리스트 다루기
망고고래
2024. 6. 18. 20:00
1. 리스트
선언
List1 = ["One", 1, "Two", True]
print(List1)
['One', 1, 'Two', True]
1) 관련 함수
len(): 길이
append(): 리스트 끝에 항목 추가
List2 = []
print(len(List2))
List2.append(1)
print(len(List2))
List2[0]
insert(): 지정 위치에 요소 삽입
List2.insert(0, 2)
List2
[2, 1]
copy(): 리스트를 복제해 새로 만듦
extend(): 리스트에서 요소를 복사해와 추가함
List3 = List2.copy()
List2.extend(List3)
List2
[2, 1, 2, 1]
pop(): 리스트의 마지막 값 제거
remove(): 리스트의 특정 위치의 값 제거
clear(): 리스트의 모든 요소 제거
2)리스트 검색: count()
Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]
ColorSelect = ""
while str.upper(ColorSelect) != "QUIT":
ColorSelect = input("Please type a color name: ")
if(Colors.count(ColorSelect) >= 1):
print("The Color exists in the list!")
elif(str.upper(ColorSelect) != "QUIT"):
print("The list doesn't contain the color.")
Please type a color name: Red
The Color exists in the list!
Please type a color name: Quit
3)리스트 정렬: sort()
Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]
for Item in Colors:
print(Item, end=" ")
print()
Colors.sort()
for Item in Colors:
print(Item, end=" ")
print()
Red Orange Yellow Green Blue
Blue Green Orange Red Yellow
+ reverse()
Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]
for Item in Colors:
print(Item, end=" ")
print()
Colors.sort()
for Item in Colors:
print(Item, end=" ")
print()
Colors.reverse()
for Item in Colors:
print(Item, end=" ")
Red Orange Yellow Green Blue
Blue Green Orange Red Yellow
Yellow Red Orange Green Blue
4) 리스트 출력: *
Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]
print(*Colors, sep='\n')
*: Colors의 각 요소를 개별 인수로 변환
print("Red", "Orange", "Yellow", "Green", "Blue", sep='\n')과 같다.
for Item in Colors: print(Item.rjust(8), sep='\n')
print('First: {0}\nSecond: {1}'.format(*Colors))
First: Red Second: Orange
5)Counter 객체
what?
리스트, 튜플, 문자열 등 이터러블 객체의 요소 빈도수 계산
how?
(1) Counter 객체 생성
① 리스트, 튜플, 문자열 등 이터러블 객체를 인수로 전달
from collections import Counter
my_list = [1, 2, 3, 4, 1, 2, 3, 1, 2, 1, 5]
counter = Counter(my_list)
print(counter) # 출력: Counter({1: 4, 2: 3, 3: 2, 4: 1, 5: 1})
②키워드 인수로 전달
counter = Counter(a=4, b=2, c=1)
print(counter) # 출력: Counter({'a': 4, 'b': 2, 'c': 1})
③딕셔너리로부터 생성
counter = Counter({'a': 4, 'b': 2, 'c': 1})
print(counter) # 출력: Counter({'a': 4, 'b': 2, 'c': 1})
(2)빈도수 확인
counter = Counter([1, 2, 3, 1, 2, 1])
print(counter[1]) # 출력: 3
print(counter[2]) # 출력: 2
print(counter[3]) # 출력: 1
from collections import Counter
MyList = [1, 2, 3, 4, 1, 2, 3, 1, 2, 1, 5]
ListCount = Counter(MyList)
print(ListCount)
for ThisItem in ListCount.items():
print("Item: ", ThisItem[0],
" Appears: ", ThisItem[1])
print("The Value 1 appears {0} times.".format(ListCount.get(1)))