Python/Python Basic

06. 리스트 List 02

HicKee 2023. 1. 13. 16:20

리스트 정렬

 

오름차순 정렬

nameList.sort()
print('오름차순으로 정렬 : ', nameList)

내림차순 정렬

nameList.sort(reverse=True)
print('내림차순으로 정렬 : ', nameList)

리스트 데이터 추가 > 마지막에 추가됨

nameList.append('이순신')
print('마지막에 추가 : ', nameList)

리스트 특정 위치에 데이터 추가

nameList.insert(2, '김유신')
print('3번째에 추가', nameList)

리스트 내의 데이터 개수확인

count = nameList.count('홍길동')
print('list내의 홍길동의 개수 :', count)

리스트 마지막 요소 삭제

nameList.pop()
print('마지막 요소를 제거 : ', nameList)

리스트 특정 데이터 삭제

nameList.remove('홍길동')
print('홍길동 삭제 함 : ', nameList)

입력을 받아서 리스트에서 삭제

 

# 첫번째 방법

nameList2 = ['홍길동', '김길동', '박길동', '최길동']
stringName = input('삭제 할 이름을 입력하세요 : ')
count2 = nameList2.count(stringName)
if count2 == 0:
    print(f'{stringName} 이름이 없습니다')
else:
    nameList2.remove(stringName)
    print(f'{stringName} 이름이 삭제 되었습니다')
print(nameList2)
# 두번째 방법

nameList3 = ['홍길동', '김길동', '박길동', '최길동']
stringName1 = input('삭제 할 이름을 입력하세요 : ')
if stringName1 in nameList3:
    nameList3.remove(stringName1)
    print(f'{stringName} 이름이 삭제 되었습니다')
else:
    print(f'{stringName} 이름이 없습니다')
print(nameList3)
# 세번째 방법 try ~ catch

nameList3 = ['홍길동', '김길동', '박길동', '최길동']
stringName1 = input('삭제 할 이름을 입력하세요 : ')
try:
    nameList3.remove(stringName1)
    print(f'{stringName1} 이름이 삭제 되었습니다')
except ValueError:
    print(f'{stringName1} 이름이 없습니다')
print(nameList3)

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

07. 리스트 List 04  (0) 2023.01.15
07. 리스트 List 03  (0) 2023.01.15
05. 리스트 List 01  (0) 2023.01.13
04. 제어문 IF  (0) 2023.01.12
03. 데이터 타입  (0) 2023.01.11