list print() and sort() 연습

Junho Song·2022년 11월 24일
0

Python

목록 보기
7/11

문제:
list, for, append, sort를 사용하여 아래의 출력값이 나오도록 코드를 작성하시오.

I have 4 items to purchase
These items are:
apple
mango
carrot
banana

I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now ['apple', 'banana', 'carrot', 'mango', 'rice']


코드:

shopping_list = ['apple', 'mango', 'carrot', 'banana']

print('I have', len(shopping_list), 'items to purchase')

print('These items are:')
for item in shopping_list:
	print(item)

print('I also have to buy rice.')
shopping_list.append('rice')
print('My shopping list is now', shopping_list)
shopping_list.sort()
print('I will sort my list now', shopping_list)

해석:

이번 코드 문제는 직관적이기 때문에 한줄한줄 자세한 해석은 생략하고 몇가지 포인트만 집고 넘어가보자.

apple
mango
carrot
banana

위와 같은 형식으로 프린트 하기 위해 for을 통한 반복문을 사용하여 한줄에 하나의 item이 프린트 되도록 하였다. 만약 print(shopping_list)를 썻다면 ['apple', 'mango', 'carrot', 'banana']와 같이 list 형태로 출력되었을 것이다.

shopping_list.append('rice')를 통해 기존의 list인 ['apple', 'mango', 'carrot', 'banana']의 마지막 인덱스에 'rice'를 추가하였다.

shopping_list.sort()를 통해 알파벳 순서대로 shopping_list에 있는 item들을 정렬하였다. sort()는 숫자 또한 정렬해준다.

profile
상위 1%의 금융데이터 분석가를 꿈꿉니다.

0개의 댓글