- 리스트 곱셈연산을 하면 아이템이 반복된다.
students = ['홍길동', '박찬호','이용규']
print(students)
studentsMul = students * 3
print(studentsMul)
['홍길동', '박찬호', '이용규']
['홍길동', '박찬호', '이용규', '홍길동', '박찬호', '이용규', '홍길동', '박찬호', '이용규']
- 리스트에 아이템 인덱스 번호 알기 위해 사용
students = ['홍길동', '강호동', '박찬호', '이용규', '박승철', '강호동', '김지은']
searchIdx = students.index('강호동')
print(f'searchIdx : {searchIdx}')
searchIdx : 1
students = ['홍길동', '강호동', '박찬호', '이용규', '박승철', '강호동', '김지은']
searchIdx = students.index('강호동',2,6) #인덱스 2 에서 5까지 있는 강호동 찾기
print(f'searchIdx : {searchIdx}')
searchIdx : 5
1~10까지의 정수가 중복되지 않고 섞여 있을 때 숫자 7의 위치를 찾는 게임
import random
sampleList = random.sample(range(1,11),10) #1~10까지 리스트 아이템 갯수 10개
selectIdx = int(input('7의 자리 입력 : '))
searchIdx = sampleList.index(7)
if searchIdx == selectIdx-1:
print('빙고!')
else:
print('ㅠㅠ')
print(f'sampleList : {sampleList}')
print(f'selectIdx : {selectIdx}')
7의 자리 입력 : 3
빙고!
sampleList : [1, 10, 7, 9, 3, 5, 8, 4, 2, 6]
selectIdx : 3
7의 자리 입력 : 3
ㅠㅠ
sampleList : [5, 6, 2, 7, 8, 1, 4, 3, 10, 9]
selectIdx : 3
- 특정 아이템의 갯수 알아내기
students = ['홍길동', '강호동', '박찬호', '이용규', '박승철', '강호동', '김지은']
print(students.count('강호동'))
2
- 특정 아이템을 삭제
students = ['홍길동', '강호동', '박찬호', '이용규', '박승철', '강호동', '김지은']
print(students)
del students[1]
print(students)
['홍길동', '강호동', '박찬호', '이용규', '박승철', '강호동', '김지은']
['홍길동', '박찬호', '이용규', '박승철', '강호동', '김지은']
students = ['홍길동', '강호동', '박찬호', '이용규', '박승철', '강호동', '김지은']
del students[1:4]
print(students)
['홍길동', '박승철', '강호동', '김지은']
import random
types = ['A','B','AB','O']
todayData = []
typeCnt =[]
for i in range(100):
type = types[random.randrange(len(types))]
todayData.append(type)
print(f'todayData : {todayData}')
print(f'todayData length: {len(todayData)}')
for type in types:
print(f'{type}형 : {todayData.count(type)}개')
todayData : ['B', 'O', 'AB', 'AB', . . . 'A', 'O', 'A']
todayData length: 100
A형 : 24개
B형 : 19개
AB형 : 31개
O형 : 26개
- 리스트와 비슷하지만 가장 큰 차이점은 한번 선언된 아이템은 변경불가 이다.
students = ('홍길동','박찬호','이용규','박승철')
print(students)
--> ('홍길동', '박찬호', '이용규', '박승철', '김지은')
- 리스트와 마찬가지로 아이템에 자동으로 부여되는 번호표가 있다.
인덱스 라고 한다.
students = ('김성예','신경도','박기준','최승철','황동석')
for i in range(len(students)):
if i % 2 ==0:
print(f'인덱스 짝수: students[{i}] : {students[i]}')
else:
print(f'인덱스 홀수: students[{i}] : {students[i]}')
인덱스 짝수: students[0] : 김성예
인덱스 홀수: students[1] : 신경도
인덱스 짝수: students[2] : 박기준
인덱스 홀수: students[3] : 최승철
인덱스 짝수: students[4] : 황동석
- 튜플 내에 아이템의 존재 유/무 파악
in 키워드 예시
students = ('홍길동','이용규','박승철','김지은')
inputname = input('학생 이름 입력 : ')
if inputname in students:
print(f'{inputname}은 우리반 학생이 맞습니다.')
else:
print(f'{inputname}은 우리반 학생이 아닙니다.')
학생 이름 입력 : ghdrlfehd
ghdrlfehd은 우리반 학생이 아닙니다.
학생 이름 입력 : 홍길동
홍길동은 우리반 학생이 맞습니다.
not in 키워드 예시
students = ('홍길동','이용규','박승철','김지은')
inputname = input('학생 이름 입력 : ')
if inputname not in students:
print(f'{inputname}은 우리반 학생이 아닙니다.')
else:
print(f'{inputname}은 우리반 학생이 맞습니다.')
학생 이름 입력 : 홍길동
홍길동은 우리반 학생이 맞습니다.
학생 이름 입력 : ghdrlfehd
ghdrlfehd은 우리반 학생이 아닙니다.
- 리스트와 달리 extend()함수 사용 불가 --> 튜플은 변경이 불가하기 때문이다.
- 덧셈 연산자 연결은 가능 --> 덧셈 연산자는 새로운 튜플을 생성하기 때문이다.
- 튜플 + 튜플 만 가능하다.
myNumbers = (1,2,5,7)
fridendNumbers = (2,4,5,7,10)
result = ()
for number in fridendNumbers:
if number not in myNumbers:
#number는 int형 이기 떄문에 튜플로 바꿔 줘야 한다.
튜플로 캐스팅하는 법은 ()괄호치고 , 를 붙여주면 된다.
myNumbers = myNumbers + (number, )
print(f'{myNumbers}')
(1, 2, 5, 7, 4, 10)
- 리스트와 동일하지만 유일하게 아이템 변경은 불가능 하다.
- 튜플은 변경이 불가능 하기 때문이다.
students = ('홍길동','박찬호','이용규','강호동','박승철','김지은')
print(f'students : {students}')
print(f'students[2:4] : {students[2:4]}')
print(f'students[:4] : {students[:4]}')
print(f'students[2:] : {students[2:]}')
print(f'students[2:-2] : {students[2:-2]}')
#슬라이싱 단계 설정도 가능. [1:4:2] -> 인덱스 1번부터3번까지 슬라이싱 후 2개씩 띄워서 출력
print(f'students[1:4:2] : {students[1:4:2]}')
students : ('홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은')
students[2:4] : ('이용규', '강호동')
students[:4] : ('홍길동', '박찬호', '이용규', '강호동')
students[2:] : ('이용규', '강호동', '박승철', '김지은')
students[2:-2] : ('이용규', '강호동')
students[1:4:2] : ('박찬호', '강호동')
- 리스트와 튜플의 가장 큰 차이점은 튜플은 아이템 변경이 불가하다는 것이다.
- 튜플은 선언 시 () 생략 가능하다.
- 리스트와 튜플은 서로 변환이 가능하다. list(), tuple()
playerScore = (9.5, 8.9, 9.2, 9.8, 8.8, 9.0)
playerScore = list(playerScore)
print(type(playerScore))
playerScore.sort()
playerScore.pop(0)
playerScore.pop(len(playerScore)-1)
playerScore = tuple(playerScore)
sum = 0
avg = 0
for i in playerScore:
sum += i
avg = sum / len(playerScore)
print(f'playerScore : {playerScore}')
print(f'총점 :{round(sum,2)}')
print(f'평균 :{round(avg,2)}')
<class 'list'>
playerScore : (8.9, 9.0, 9.2, 9.5)
총점 :36.6
평균 :9.15
- 튜플은 변경이 불가해 정렬이 불가 할것 같지만 sorted()함수를 사용하면 가능하다.
- 대신에 sorted()함수를 이용해 정렬 후에는 리스트로 반환된다.
students = ('홍길동','박찬호','이용규','강호동','박승철','김지은')
print(f'students : {students}')
print(f'students type: {type(students)}')
#sorted함수는 따로 변수에 저장
sortedStudents = sorted(students)
print(f'students : {sortedStudents}')
print(f'students type: {type(sortedStudents)}') #-->튜플이 정렬되고 리스트로 반환
students : ('홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은')
students type: <class 'tuple'>
students : ['강호동', '김지은', '박승철', '박찬호', '이용규', '홍길동']
students type: <class 'list'>
- 리스트 for문과 동일하다.
예시1.
studentCnts = ((1,19),(2,20),(3,22),(4,18),(5,21))
for classNo, cnt in studentCnts:
print(f'{classNo}학급 학생수 : {cnt}')
1학급 학생 수 : 19
2학급 학생 수 : 20
3학급 학생 수 : 22
4학급 학생 수 : 18
5학급 학생 수 : 21
scores = (('국어',58),('영어',77),('수학',89),('과학',99),('국사',50))
minScore = 60
#방법1.
for sub, score in scores:
if score < minScore:
print(f'{sub}과목 과락 점수 : {score}')
#방법2.
for item in scores:
if item[1] < minScore:
print(f'{item[0]}과목 ㅗ가락 점수 : {item[1]}')
국어과목 과락 점수 : 58
국사과목 과락 점수 : 50
국어과목 과락 점수 : 58
국사과목 과락 점수 : 50
studentCnts = ((1,18),(2,19),(3,23),(4,21),(5,20),(6,22),(7,17))
minClassNo = 0;maxClassNo = 0
minCnt = 0;maxCnt = 0
for classNo, cnt in studentCnts:
if minCnt == 0 or minCnt>cnt:
minClassNo = classNo
minCnt = cnt
if maxCnt < cnt:
maxCnt = cnt
maxClassNo = classNo
print(f'학생수가 가장 많은 {maxClassNo}학급: {maxCnt}명')
print(f'학생수가 가장 적은 {minClassNo}학급: {minCnt}명')
학생수가 가장 많은 3학급: 23명
학생수가 가장 적은 7학급: 17명
studentCnts = ((1,18),(2,19),(3,23),(4,21),(5,20),(6,22),(7,17))
minClassCnt = 0;maxClassCnt = 0
minCnt = 0; maxCnt = 0
n = 0
while n < len(studentCnts):
if minCnt == 0 or studentCnts[n][1] < minCnt:
minCnt = studentCnts[n][1]
minClassCnt = studentCnts[n][0]
if studentCnts[n][1] > maxCnt:
maxCnt = studentCnts[n][1]
maxClassCnt = studentCnts[n][0]
n+=1
print(f'가장 학생수가 적은 학급 : {minClassCnt}학급({minCnt}명)')
print(f'가장 학생수가 많은 학급 : {maxClassCnt}학급({maxCnt}명)')
가장 학생수가 적은 학급 : 7학급(17명)
가장 학생수가 많은 학급 : 3학급(23명)
- 키(key)와 값(value)를 이용해서 자료관리를 한다.
- 인덱스가 없고 키(key)가 인덱스 역할을 한다.
- 키(key)는 사용자가 정의한다.
- 값(value)는 중복되고 괜찮지만 키(key)는 중복되면 안된다.
- {}를 이용해서 선언하고 '키 : 값'의 형태로 아이템을 정의한다.
students = {'s1':'홍길동', 's2':'박찬호','s3':'강호동', 's4':['박세리','박공주']}
print(students)
print(type(students))
{'s1': '홍길동', 's2': '박찬호', 's3': '강호동', 's4': ['박세리', '박공주']}
<class 'dict'>
- 키 값을 이용해서 값을 조회
- 없는 키 값을 조회하려 한다면 오류가 뜬다.
- get(키)함수 사용해 조회도 가능하다.
- get(키)함수는 없는 키 값을 조회한다면 오류가 뜨지 않고 None으로 출력된다.
myInfo = {
'이름':'홍길동',
'전공':'python',
'메일':'gildong@gmail.com',
'학년':3,
'주소':'서울',
'취미':['수영','축구']
}
print(myInfo)
#키 값이용
print(myInfo['이름'])
print(myInfo['메일'])
print(myInfo['취미'])
#get()이용
print(myInfo.get('이름'))
print(myInfo.get('전공'))
print(myInfo.get('학년'))
print(myInfo.get('주소'))
print(myInfo.get('dpfj'))
{'이름': '홍길동', '전공': 'python', '메일': 'gildong@gmail.com', '학년': 3, '주소': '서울', '취미': ['수영', '축구']}
홍길동
gildong@gmail.com
['수영', '축구']
홍길동
python
3
서울
None
- 딕셔너리이름 [키] = 값 형태로 아이템 추가
- 추가하려는 키가 이미 있다면 기존값이 변경된다.
myInfo = {}
myInfo['이름'] = '홍길동'
myInfo['전공'] = 'computer'
myInfo['메일'] = 'gildong@gmail.com'
myInfo['학년'] = 3
myInfo['주소'] = 'korea'
myInfo['취미'] = ['수영','축구']
print(myInfo)
#추가하려는 키가 이미 있다면 기존값이 변경 된다.
myInfo['메일'] = 'room324@naver.com'
print(myInfo)
{'이름': '홍길동', '전공': 'computer', '메일': 'gildong@gmail.com', '학년': 3, '주소': 'korea', '취미': ['수영', '축구']}
{'이름': '홍길동', '전공': 'computer', '메일': 'room324@naver.com', '학년': 3, '주소': 'korea', '취미': ['수영', '축구']}
factorialDic = {}
for i in range(11):
if i == 0:
factorialDic[i] = 1
else:
for j in range(1,i+1):
factorialDic[i] = factorialDic[i-1]*j
print(f'factorialDic : {factorialDic}')
factorialDic : {0: 1, 1: 1, 2: 2, 3: 6, 4: 24,
5: 120, 6: 720, 7: 5040, 8: 40320, 9: 362880, 10: 3628800}
- 딕셔너리 이름[키] = 값 형태로 변경
- 추가와 같지만 키값이 같다면 기존값이 변경이 된다.
scores = {'kor':88,'eng':55,'mat':85,'sci':57,'his':82}
print(scores)
minScore = 60
fStr = 'f(재시험)'
if scores['kor'] < minScore: scores['kor'] = fStr
if scores['eng'] < minScore: scores['eng'] = fStr
if scores['mat'] < minScore: scores['mat'] = fStr
if scores['sci'] < minScore: scores['sci'] = fStr
if scores['his'] < minScore: scores['his'] = fStr
print(scores)
{'kor': 88, 'eng': 55, 'mat': 85, 'sci': 57, 'his': 82}
{'kor': 88, 'eng': 'f(재시험)', 'mat': 85, 'sci': 'f(재시험)', 'his': 82}
myBodyInfo = {'이름':'gildong','몸무게':83.0,'신장':1.8}
myBMI = myBodyInfo['몸무게'] / (myBodyInfo['신장']**2)
print(f'myBodyInfo : {myBodyInfo}')
print(f'myBMI : {round(myBMI,4)}')
date = 0
while True:
date +=1
myBodyInfo['몸무게'] = round(myBodyInfo['몸무게'] + (-0.3),2)
myBodyInfo['신장'] = round(myBodyInfo['신장'] + 0.001,3)
myBMI = round(myBodyInfo['몸무게'] / (myBodyInfo['신장'] ** 2),2)
if date>=30:
break
print('몸무게 : {}'.format(myBodyInfo['몸무게']))
print('신장 : {}'.format(myBodyInfo['신장']))
print('BMI : {}'.format(myBMI))
myBodyInfo : {'이름': 'gildong', '몸무게': 83.0, '신장': 1.8}
myBMI : 25.6173
몸무게 : 74.0
신장 : 1.83
BMI : 22.84
- 전체 키(key)와 값(value)를 조회할 수 있다.
- 결과의 type은 리스트가 아니라 dic_keys나 dic_vlues이다
- 따라서 리스트로 사용하고 싶다면 리스트로 변환해야 한다.
- 리스트로 변환한 후에는 리스트와 같이 조회 가능
scores = {'kor':88,'eng':55,'mat':85,'sci':57,'his':82}
print(scores)
minScore = 60
fStr = 'F(재시험)'
fDic = {}
for key in scores.keys():
if scores[key] < minScore:
scores[key] = fStr
fDic[key] = fStr
print(f'score : {scores}')
print(f'fDic : {fDic}')
{'kor': 88, 'eng': 55, 'mat': 85, 'sci': 57, 'his': 82}
score : {'kor': 88, 'eng': 'F(재시험)', 'mat': 85, 'sci': 'F(재시험)', 'his': 82}
fDic : {'eng': 'F(재시험)', 'sci': 'F(재시험)'}
- del 딕셔너리이름[키] --> 해당 아이템 딕셔너리에서 삭제
- 딕셔너리이름.pop(키) --> 해당 아이템 딕셔너리에서 삭제
- pop()함수 이용 시 변수로 지정하고 지정한 변수 출력하면 삭제된 아이템 value값 출력 가능
del 키워드 이용
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':3, '취미':['농구', '게임']}
print(f'memInfo: {memInfo}')
del memInfo['메일']
print(f'memInfo: {memInfo}')
del memInfo['취미']
print(f'memInfo: {memInfo}')
memInfo: {'이름': '홍길동', '메일': 'gildong@gmail.com', '학년': 3, '취미': ['농구', '게임']}
memInfo: {'이름': '홍길동', '학년': 3, '취미': ['농구', '게임']}
memInfo: {'이름': '홍길동', '학년': 3}
pop()함수 이용
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':3, '취미':['농구', '게임']}
print(f'memInfo: {memInfo}')
returnValue = memInfo.pop('이름')
print(f'memInfo: {memInfo}')
print(f'returnValue: {returnValue}')
print(f'returnValue type: {type(returnValue)}')
memInfo: {'이름': '홍길동', '메일': 'gildong@gmail.com', '학년': 3, '취미': ['농구', '게임']}
memInfo: {'메일': 'gildong@gmail.com', '학년': 3, '취미': ['농구', '게임']}
returnValue: 홍길동
returnValue type: <class 'str'>
scores ={'s1':8.9,'s2':8.1,'s3':8.5,'s4':9.8,'s5':8.8}
minScore = 10; minKey = ''
maxScore = 0; maxKey = ''
for key in scores.keys():
if scores[key] < minScore:
minScore = scores[key]
minKey = key
if scores[key] > maxScore:
maxScore = scores[key]
maxKey = key
print('minScore = {}'.format(minScore))
print('minScoreKey = {}'.format(minKey))
print('maxScore = {}'.format(maxScore))
print('maxScoreKey = {}'.format(maxKey))
del scores[minKey]
del scores[maxKey]
print('scores : {}'.format(scores))
minScore = 8.1
minScoreKey = s2
maxScore = 9.8
maxScoreKey = s4
scores : {'s1': 8.9, 's3': 8.5, 's5': 8.8}
- clear()함수는 딕셔너리 아이템들을 모두 삭제한다.
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':3, '취미':['농구', '게임']}
print('memInfo: {}'.format(memInfo))
memInfo.clear()
print('memInfo: {}'.format(memInfo))
memInfo: {'이름': '홍길동', '메일': 'gildong@gmail.com', '학년': 3, '취미': ['농구', '게임']}
memInfo: {}
개인정보에 '연락처'와'주민등록번호' 기 있다면 삭제하는 코드 작성
myInfo = {'이름':'Hong Gildong',
'나이':'30',
'연락처': '010-1234-5678',
'주민등록번호':'840315-1234567',
'주소':'대한민국 서울'}
print('myInfo: {}'.format(myInfo))
<#따로 삭제할 키값의 리스트 작성>
deleteItems = ['연락처', '주민등록번호']
for item in deleteItems:
if (item in myInfo):
del myInfo[item]
print('myInfo: {}'.format(myInfo))
myInfo: {'이름': 'Hong Gildong', '나이': '30', '연락처': '010-1234-5678', '주민등록번호': '840315-1234567', '주소': '대한민국 서울'}
myInfo: {'이름': 'Hong Gildong', '나이': '30', '주소': '대한민국 서울'}