Tech Blog of Pinomaker
Published 2022. 6. 6. 13:40
[Python] 리스트(2) Language/Python

리스트는 문자열과 같이 슬라이스를 이용 할 수 있다.

# 리스트[start : stop : step]

alp = list("abcdefghij")
print(alp) #["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

print(alp[:]) # ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(alp[: :]) # ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(alp[::-1]) # ["j", "i", "h", "g", "f", "e", "d", "c", "b", "a"]

 

리스트를  수정 할 수 있는 방법은 아래와 같다.

sports = ["축구", "야구", "볼링", "농구", "배구", "골프"]

sports[0:2] = ["하키"] # ["하키", "하키", "볼링", "농구", "배구", "골프"]

menu = []
menu.insert(0, "감자")
menu.insert(0, "토마토")

#menu = ["토마토", "감자"]
menu.insert(1,  "김")
#menu = ["토마토","김", "감자"]

 

리스트 메소드를 이용한 항목 삭제

sports = ["축구", "야구", "볼링", "농구", "배구", "골프"]

#remove
sports.remove("축구")
print(sports) #["야구", "볼링", "농구", "배구", "골프"]

#pop
sports.pop(0) # 0번째인 야구 삭제
sports.pop() #마지막 첨자인 골프 삭제
print(sports) # ["볼링", "농구", "배구"]

#del
del sports[0] # 0번째, 볼링 삭제
print(sports) # ["농구", "배구"]

#clear
kpop.clear() 
print(sports) #[]

 

리스트 메소드를 이용한 추가, 연결, 반복

#extend : 리스트 연결
sports = ["축구", "야구", "볼링"]
sports2 = ["농구", "배구", "골프"]

sports.extend(sports2)
print(sports) #["축구", "야구", "볼링", "농구", "배구", "골프"]

# +연산자, * 연산자
korean = ["불고기", "김치"]
japanese = ["초밥", "덮밥"]
food = korean + japanese
print(food) # ["불고기", "김치", "초밥", "덮밥"]

 

리스트 메소드를 이용한 정렬

# reverse를 이용한 뒤집기
menu = ["불고기", "김치",  "소고기", "떡볶이"]
print(menu.reverse()) #["떡볶이", "소고기", "김치", "불고기"]

# sort를 이용한 정렬
menu.sort()
print(menu) #['김치', '떡볶이', '불고기', '소고기']

menu.sort(reverse = True)
print(menu) #['소고기', '불고기', '떡볶이', '김치']

# sorted를 이용한 정렬 리스트 반환
menuList = sorted(menu) 
print(menuList) # ['김치', '떡볶이', '불고기', '소고기']

'Language > Python' 카테고리의 다른 글

[Python] 함수  (0) 2022.06.12
[Python] 딕셔너리  (0) 2022.06.12
[Python] 리스트(1)  (0) 2022.06.06
[Python] requests와 json을 이용한 http 통신하기.  (0) 2022.06.04
[Python] 튜플  (0) 2022.05.30
profile

Tech Blog of Pinomaker

@pinomaker

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!