리스트 길이: 리스트에 저장된 아이템 개수
students = ['홍길동','이용규','박찬호']
for i in range(len(students)):
print('students[{}] : {}'.format(i, students[i]))
students = ['홍길동','이용규','박찬호']
n = 0
sLength = len(students)
while n < sLength:
print('n : {}'.format(n))
print('students[{}] : {}'.format(n, students[n]))
n += 1
myFavoriteSports = ['수영','배구','야구','조깅']
for item in myFavoriteSports:
print(item)
studentsCnt = [[1,19],[2,19],[3,20],[4,22],[5,18]]
for classNo, cnt in studentsCnt:
print('{}학급 학생수: {}'.format(classNo, cnt))
minScore = 60
scores = [['국어', 69],['수학', 50], ['영어', 94], ['과학', 70], ['국사', 87]]
for subject, score in scores:
if score >= minScore:
continue
print(f'과락 과목: {subject}, 점수: {score}')
cars = ['그랜저', '소나타','말리부','카니발','쏘렌토']
n = 0
while n < len(cars):
print(cars[n])
n +=1
cars = ['그랜저','소나타','말리부','카니발','쏘렌토']
n=0
flag = True
while flag:
print(cars[n])
n+=1
if n == len(cars):
flag = False
cars = ['그랜저','소나타','말리부','카니발','쏘렌토']
n=0
while True:
print(cars[n])
n += 1
if n == len(cars):
break
studentCnts = [[1,18], [2,19], [3,23], [4,21], [5,20], [6,22], [7,17]]
sum = 0
avg = 0
n = 0
while n < len(studentCnts):
classNo = studentCnts[n][0]
studentCnt = studentCnts[n][1]
print('{}학급 학생수: {}명'.format(classNo, studentCnt))
n +=1
sum += studentCnt
avg = sum / len(studentCnts)
print(f'총 학생 수: {sum}명')
print(f'평균 학생 수: {avg}명')
studentCnts = [['1학급',18], ['2학급',19], ['3학급',23], ['4학급',21], ['5학급',20]]
maxClass = 0
minClass = 0
maxCnt = 0
minCnt = 0
n = 0
while n < len(studentCnts):
if minCnt == 0 or studentCnts[n][1] < minCnt:
minClass = studentCnts[n][0]
minCnt = studentCnts[n][1]
if studentCnts[n][1] > maxCnt:
maxClass = studentCnts[n][0]
maxCnt = studentCnts[n][1]
n += 1
print(f'학생 수가 가장 적은 학급(학생수): {minClass}({minCnt})')
print(f'학생 수가 가장 많은 학급(학생수): {maxClass}({maxCnt})')
💥 minCnt == 0 일 때도 배정
enumerate()
아이템 열거
message = input('메시지 입력: ')
cnt = 0
for idx, value in enumerate(message):
if value == ' ':
cnt += 1
print(f'공백의 갯수는 {cnt}개 입니다')
append()
: 마지막 인덱스에 아이템 추가
insert()
: 특정 위치에 아이템 추가
words = ['I', 'a', 'boy']
words.insert(1, 'am')
for word in words:
print('{} '.format(word), end = '')
numbers = [1, 3, 6, 11, 45, 54, 62, 74]
inputNumber = int(input('숫자 입력: '))
insertIdx = 0
for idx, value in enumerate(numbers):
if insertIdx==0 and inputNumber < value:
insertIdx = idx
numbers.insert(insertIdx, inputNumber)
print(numbers)
💥 insertIdx ==0 이어야 처음(최초) 만족하는 자리 찾아감
pop()
: 마지막 인덱스에 해당하는 아이템 삭제
pop(n)
: n인덱스에 해당하는 아이템 삭제
rValue = students.pop()
print(rValue)
remove()
: 특정 아이템 삭제(첫번째 아이템 하나만)
여러 아이템 삭제 => while문 이용
students = ['홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은', '강호동']
students.remove('강호동')
while '강호동' in students:
students.remove('강호동')
del
: 특정 아이템 삭제
del students[2:4]
extend()
: 리스트에 또 다른 리스트 연결(확장)
+
: 또 다른 변수에 리스트 연결
myFavoriteNumbers = [1, 3, 5, 6, 7]
friendFavoriteNumbers = [2, 3, 5, 8, 10]
addlist = myFavoriteNumbers + friendFavoriteNumbers
result = []
for number in addlist:
if number not in addlist:
result.append(number)
Sort()
: 아이템 정렬 /sort(reverse = True)
: 내림차순
playerScore = [9.5, 8.9, 9.2, 9.8, 8.8, 9.0]
playerScore.sort()
playerScore.pop(len(playerScore)-1)
playerScore.pop(0)
print(playerScore)
sum = 0
for score in playerScore:
sum += score
print(f'총점 : %.2f' %sum)
reverse()
: 리스트 아이템 순서 뒤집기
secret = '27156231'
secretList = []
solvedList = ''
for cha in secret:
secretList.append(int(cha)) #문자->숫자가 되어서 list에 담김
secretList.reverse()
print('secretList: {}'.format(secretList))
val = secretList[0]*secretList[1]
secretList.insert(2, val)
val = secretList[3]*secretList[4]
secretList.insert(5, val)
val = secretList[6]*secretList[7]
secretList.insert(8, val)
val = secretList[9]*secretList[10]
secretList.insert(11, val)
💥 SolvedList는?
리스트 슬라이싱: 원하는 아이템만 뽑아내기([n:m])
[2:4] = 2<= n < 4
students = ['홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은']
print(students[2:4])
출력값: ['이용규', '강호동']
students = ['홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은']
print(students[-4:-2])
출력값: ['이용규', '강호동']
numbers = [2, 50, 0.12, 1, 9, 7, 17, 35, 100, 3.14]
print(numbers[2:-2:2])
print(numbers[:-2:2])
print(numbers[2::2])
[0.12, 9, 17]
[2, 0.12, 9, 17]
[0.12, 9, 17, 100]
students = ['강호동', '박찬호', '이용규', '박승철', '김지은']
students[1:3] = ['park chanho', 'lee yonggyu']
개수가 다르다면?
students = ['강호동', '박찬호', '이용규', '박승철', '김지은']
students[1:3] = ['park chanho']
print(students)
['강호동', 'park chanho', '박승철', '김지은'] = 길이 짧아짐
Slice(n,m) : n<=idx<m 추출
students = ['강호동', '박찬호', '이용규', '박승철', '김지은']
print(students[slice(2, 4)])
['이용규', '박승철']
리스트 곱셈: 리스트 아이템 반복
numbers = [2, 50, 0.12, 1, 9]
numbersMul = numbers * 2
print(numbersMul)
출력값: [2, 50, 0.12, 1, 9, 2, 50, 0.12, 1, 9]
Index()
: 아이템의 인덱스 찾기
numbers = [2, 50, 0.12, 2, 9]
searchIdx = numbers.index(2)
print(searchIdx)
출력값: 0 (가장 앞 index만 출력)
searchIdx = numbers.index(2, 2, 4)
출력값: 3 (범위 지정(2:4))
import random
sampleList = random.sample(range(1, 11),10)
selectIdx = int(input('숫자 7의 위치 입력: '))
searchIdx = sampleList.index(7)
if selectIdx == searchIdx:
print('빙고!!')
else: print('ㅜㅜ')
print(sampleList)
print(searchIdx)
count()
: 특정 아이템 개수
students = ['홍길동', '강호동', '박찬호', '이용규', '박승철', '김지은', '강호동']
searchCnt = students.count('강호동')
print(searchCnt)
import random
types = ['A','B','O','AB']
todayData = []
random.randrange(len(types)) => 0,1,2,3 중 하나 추출
types[random.randrange(len(types))] => A,B,O,AB 중 하나 추출
for i in range(100):
type = types[random.randrange(len(types))]
todayData.append(type)
for type in types:
print('{}형 \t : {}개'.format(type, todayData.count(type)))