생능출판사 (가칭)"데이터과학 파이썬" 코드 7장

7.1 리스트는 무엇이고 왜 필요한가

In [1]:
height = 178.9    # float ŸÀÔÀÇ µ¥ÀÌÅ͸¦ ÀúÀåÇÑ´Ù.
In [2]:
height1 = 178.9    # float ŸÀÔÀÇ µ¥ÀÌÅ͸¦ ÀúÀåÇÑ´Ù.
height2 = 173.5    # float ŸÀÔÀÇ µ¥ÀÌÅ͸¦ ÀúÀåÇÑ´Ù.
height3 = 166.1    # float ŸÀÔÀÇ µ¥ÀÌÅ͸¦ ÀúÀåÇÑ´Ù.
height4 = 164.3    # float ŸÀÔÀÇ µ¥ÀÌÅ͸¦ ÀúÀåÇÑ´Ù.
height5 = 176.4    # float ŸÀÔÀÇ µ¥ÀÌÅ͸¦ ÀúÀåÇÑ´Ù.
In [3]:
heights = [178.9, 173.5, 166.1, 164.3, 176.4]
heights
Out[3]:
[178.9, 173.5, 166.1, 164.3, 176.4]

7.2 ¿©·¯°³ÀÇ Ç׸ñÀÌ µé¾î°¡´Â ¸®½ºÆ®¸¦ ¸¸µéÀÚ

In [4]:
bts = ['V', 'Jungkook', 'Jimin']
In [5]:
bts = []
In [6]:
bts = []
bts.append("V")
bts
Out[6]:
['V']
In [7]:
bts.append("Jin")
bts.append("Suga")
bts
Out[7]:
['V', 'Jin', 'Suga']
In [8]:
bts = ['V', 'Jin', 'Suga', 'Jungkook']
bts = bts + ['RM']   # µ¡¼À ¿¬ÀÚÀÚ·Î ¸â¹ö 'RM'À» Ãß°¡ÇÔ
bts
Out[8]:
['V', 'Jin', 'Suga', 'Jungkook', 'RM']
In [9]:
list(range(5))       # 0¿¡¼­ 5»çÀÌÀÇ Á¤¼ö¿­À» »ý¼º(5´Â Æ÷ÇԾȵÊ)
Out[9]:
[0, 1, 2, 3, 4]
In [10]:
list(range(0, 5))    # list(range(5))¿Í µ¿ÀÏÇÑ °á°ú 
Out[10]:
[0, 1, 2, 3, 4]
In [11]:
list(range(0, 5, 1)) # list(range(0, 5))¿Í µ¿ÀÏÇÑ °á°ú
Out[11]:
[0, 1, 2, 3, 4]
In [12]:
list(range(0, 5, 2)) # »ý¼ºÇÏ´Â °ªÀ» 2¾¿ Áõ°¡½ÃÅ´ 
Out[12]:
[0, 2, 4]
In [13]:
list(range(2, 5))    # 2¿¡¼­ 5-1±îÁöÀÇ ¿¬¼ÓµÈ ¼ö 2, 3, 4À» »ý¼º
Out[13]:
[2, 3, 4]

7.3 ¸®½ºÆ® ¿¬»êÀ» Çغ¸ÀÚ

In [14]:
bts = ['V', 'J-Hope'] + ['RM', 'Jungkook', 'Jin']
bts
Out[14]:
['V', 'J-Hope', 'RM', 'Jungkook', 'Jin']
In [15]:
numbers = [10, 20, 30] + [40, 50, 60]
numbers
Out[15]:
[10, 20, 30, 40, 50, 60]
In [16]:
mystery = [0, 1, 2] * 3   # [0, 1, 2]°¡ 3ȸ ¹Ýº¹µÇ¾î ÀúÀåµÊ
mystery
Out[16]:
[0, 1, 2, 0, 1, 2, 0, 1, 2]
In [17]:
bts = ['V', 'J-Hope', 'RM', 'Jungkook', 'Jin', 'Jimin', 'Suga']
'V' in bts
Out[17]:
True
In [18]:
'V' not in bts
Out[18]:
False

LAB7-1

ÀÔ·ÂÀ» ¹Þ¾Æ ¸ÀÀÖ´Â °úÀÏÀÇ ¸®½ºÆ®¸¦ ¸¸µé¾î º¸ÀÚ

In [19]:
fruits = []
 
name = input('ÁÁ¾ÆÇÏ´Â °úÀÏÀÇ À̸§À» ÀÔ·ÂÇϽÿÀ: ')
fruits.append(name)
name = input('ÁÁ¾ÆÇÏ´Â °úÀÏÀÇ À̸§À» ÀÔ·ÂÇϽÿÀ: ')
fruits.append(name)
name = input('ÁÁ¾ÆÇÏ´Â °úÀÏÀÇ À̸§À» ÀÔ·ÂÇϽÿÀ: ')
fruits.append(name)
 
name = input('°úÀÏÀÇ À̸§À» ÀÔ·ÂÇϼ¼¿ä: ')
if name in fruits:
    print('ÀÌ °úÀÏÀº ´ç½ÅÀÌ ÁÁ¾ÆÇÏ´Â °úÀÏÀÔ´Ï´Ù.')
else:
    print('ÀÌ °úÀÏÀº ´ç½ÅÀÌ ÁÁ¾ÆÇÏ´Â °úÀÏÀÌ ¾Æ´Õ´Ï´Ù.')
ÁÁ¾ÆÇÏ´Â °úÀÏÀÇ À̸§À» ÀÔ·ÂÇϽÿÀ: »ç°ú
ÁÁ¾ÆÇÏ´Â °úÀÏÀÇ À̸§À» ÀÔ·ÂÇϽÿÀ: ¹è
ÁÁ¾ÆÇÏ´Â °úÀÏÀÇ À̸§À» ÀÔ·ÂÇϽÿÀ: ±Ö
°úÀÏÀÇ À̸§À» ÀÔ·ÂÇϼ¼¿ä: »ç°ú
ÀÌ °úÀÏÀº ´ç½ÅÀÌ ÁÁ¾ÆÇÏ´Â °úÀÏÀÔ´Ï´Ù.

7.4 내장함수를 이용해서 리스트를 알차게 이용하자

In [20]:
slist1 = ['Kim', 178.9, 'Park', 173.5, 'Lee', 176.1]
slist1
Out[20]:
['Kim', 178.9, 'Park', 173.5, 'Lee', 176.1]
In [21]:
slist1[0], slist1[2], slist1[4]
Out[21]:
('Kim', 'Park', 'Lee')
In [22]:
slist2 = [ ['Kim', 178.9], ['Park', 173.5], ['Lee', 176.1] ]
slist2
Out[22]:
[['Kim', 178.9], ['Park', 173.5], ['Lee', 176.1]]
In [23]:
type(slist1)
Out[23]:
list
In [24]:
type(slist2)
Out[24]:
list
In [25]:
n_list = [200, 700, 500, 300, 400]
len(n_list)
Out[25]:
5
In [26]:
max(n_list)
Out[26]:
700
In [27]:
min(n_list)
Out[27]:
200
In [28]:
sum(n_list)
Out[28]:
2100
In [29]:
sum(n_list) / len(n_list)  # ÀüüÀÇ ÇÕÀ» ¿ø¼ÒÀÇ °³¼ö·Î ³ª´©¸é Æò±Õ°ªÀ» ¾òÀ» ¼ö ÀÖ´Ù
Out[29]:
420.0
In [30]:
list(range(1,11))
Out[30]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [31]:
a_list = [0, '']
In [32]:
any(n_list)
Out[32]:
True
In [33]:
any(a_list)
Out[33]:
False

LAB 7-2 : 리스트에 인구를 저장해보자

  • ¼¼ µµ½Ã¿¡ ´ëÀü(daejeon)À» Ãß°¡ÇØ º¸µµ·Ï ÇÏÀÚ. ´ëÀüÀÇ Àα¸´Â 1,531õ¸íÀ̶ó°í °¡Á¤ÇÏÀÚ. ±×¸®°í ÀÌ ³× µµ½ÃÁß¿¡¼­ °¡Àå Àα¸°¡ ¸¹Àº µµ½ÃÀÇ Àα¸¿Í °¡Àå Àα¸°¡ ÀûÀº µµ½ÃÀÇ Àα¸, ±×¸®°í ³× µµ½ÃÀÇ Àα¸ÀÇ Æò±ÕÀ» Ãâ·ÂÇØ º¸µµ·Ï ÇÏÀÚ.
In [34]:
# Àα¸ Åë°è(´ÜÀ§: õ¸í) 
Seoul = 9765 
Busan = 3441 
Incheon = 2954 
city_pop = [ Seoul, Busan, Incheon ] # º¯¼öµé·Î ¸®½ºÆ® »ý¼º
print(city_pop)                                           # ¸®½ºÆ® µ¥ÀÌÅ͸¦ Ãâ·Â 
[9765, 3441, 2954]
In [35]:
# <¹®Á¦¿¡¼­ Á¦½ÃµÈ Äڵ带 ¿©±â¿¡ »ðÀÔÇÑ´Ù>
Daejeon = 1531
city_pop.append(Daejeon)

max_pop = 0
min_pop = 1000000
pop_sum = 0
n = 0

for pop in city_pop:    # ¼øȯ¹®À» µ¹¸é¼­ ÃÖ´ñ°ª, ÃÖ¼Ú°ªÀ» ±¸ÇÑ´Ù
    if pop > max_pop :
        max_pop = pop
    if pop < min_pop :
        min_pop = pop
    pop_sum += pop
    n += 1

print('ÃÖ´ë Àα¸:', max_pop)
print('ÃÖ¼Ò Àα¸:', min_pop)
print('Æò±Õ Àα¸:', pop_sum / n)
ÃÖ´ë Àα¸: 9765
ÃÖ¼Ò Àα¸: 1531
Æò±Õ Àα¸: 4422.75

7.5 인덱스를 사용하여 리스트의 항목에 접근하기

In [36]:
 letters = ['A', 'B', 'C', 'D', 'E', 'F'] 
In [37]:
letters[0]  # ¸®½ºÆ®ÀÇ Ã¹ Ç׸ñ¿¡ Á¢±Ù
Out[37]:
'A'
In [38]:
letters[1] 
Out[38]:
'B'
In [39]:
letters[2] 
Out[39]:
'C'
In [40]:
letters[-1]
Out[40]:
'F'
In [41]:
bts = ['V', 'RM', 'Jungkook', 'J-Hop', 'Suga', 'Jin', 'Jimin']
len(bts)          # ¸®½ºÆ®ÀÇ ¿ø¼Ò °³¼ö¸¦ ¾ò´Â´Ù
Out[41]:
7
In [42]:
bts[len(bts)-1]  # ¸¶Áö¸· ¿ø¼Ò
Out[42]:
'Jimin'
In [43]:
bts[-1]           # À½¼ö À妽º·Î ¸¶Áö¸· ¿ø¼Ò¸¦ ½±°Ô Á¢±ÙÇÒ ¼ö ÀÖ´Ù
Out[43]:
'Jimin'
In [44]:
min(bts)        # ¸®½ºÆ® ¿ø¼Ò Áß °¡Àå ÀÛÀº °ªÀ» ã´Â´Ù. (¹®ÀÚ¿­Àº »çÀü½Ä ¼ø¼­)
Out[44]:
'J-Hop'
In [45]:
max(bts)        # ¸®½ºÆ® ¿ø¼Ò Áß °¡Àå Å« °ªÀ» ã´Â´Ù. (¹®ÀÚ¿­Àº »çÀü½Ä ¼ø¼­)
Out[45]:
'V'
In [46]:
letters = ['A', 'B', 'C', 'D', 'E', 'F']
In [47]:
letters[0]
Out[47]:
'A'
In [48]:
letters[1]
Out[48]:
'B'
In [49]:
letters[2]
Out[49]:
'C'
In [50]:
letters[-1]
Out[50]:
'F'
In [51]:
alist = ['a', 'aa', 'ff', 'f', 'b', 'c']
len(alist)          # ¸®½ºÆ®ÀÇ ¿ø¼Ò °³¼ö¸¦ ¾ò´Â´Ù
Out[51]:
6
In [52]:
alist[len(alist)-1] # ¸¶Áö¸· ¿ø¼Ò
Out[52]:
'c'
In [53]:
alist[len(alist)-1] # ¸¶Áö¸· ¿ø¼Ò
Out[53]:
'c'
In [54]:
min(alist)        # ¸®½ºÆ® ¿ø¼Ò Áß °¡Àå ÀÛÀº °ªÀ» ã´Â´Ù. (¹®ÀÚ¿­Àº »çÀü½Ä ¼ø¼­)
Out[54]:
'a'
In [55]:
max(alist)        # ¸®½ºÆ® ¿ø¼Ò Áß °¡Àå Å« °ªÀ» ã´Â´Ù. (¹®ÀÚ¿­Àº »çÀü½Ä ¼ø¼­)
Out[55]:
'ff'

7.6 리스트를 원하는 모양으로 자르는 슬라이싱

In [56]:
letters = ['A', 'B', 'C', 'D', 'E', 'F'] 
letters[2:5]
Out[56]:
['C', 'D', 'E']
In [57]:
letters[:3]
Out[57]:
['A', 'B', 'C']
In [58]:
letters[3:] 
Out[58]:
['D', 'E', 'F']
In [59]:
letters[:] 
Out[59]:
['A', 'B', 'C', 'D', 'E', 'F']
In [60]:
letters[::2] 
Out[60]:
['A', 'C', 'E']
In [61]:
letters[::-1]       # µÚ¿¡¼­ºÎÅÍ ¾ÕÀ¸·Î Àоî¿À¸ç ¿ø¼Ò¸¦ »ý¼ºÇÑ´Ù 
Out[61]:
['F', 'E', 'D', 'C', 'B', 'A']

LAB7-3

µµ½ÃÀÇ Àα¸ ÀÚ·á¿¡ ´ëÇÑ ½½¶óÀ̽ÌÀ» Çغ¸ÀÚ

In [62]:
# ´ÙÀ½°ú °°Àº ¸®½ºÆ®°¡ »ý¼ºµÇ¾î ÀÖ´Ù. 
population = ["Seoul", 9765, "Busan", 3441, "Incheon", 2954]

print('¼­¿ï Àα¸:', population[1])     # ¹®Á¦ 1)
print('ÀÎõ Àα¸:', population[-1])    # ¹®Á¦ 2)

cities = population[0::2]             # ¹®Á¦ 3)
print('µµ½Ã ¸®½ºÆ®:', cities)
pops = population[1::2]               # ¹®Á¦ 4)
print('Àα¸ÀÇ ÇÕ:', sum(pops))
¼­¿ï Àα¸: 9765
ÀÎõ Àα¸: 2954
µµ½Ã ¸®½ºÆ®: ['Seoul', 'Busan', 'Incheon']
Àα¸ÀÇ ÇÕ: 16160

7.7 리스트의 원소 값을 조작해 보자

In [63]:
slist = ['Kim', 178.9, 'Park', 173.5, 'Lee', 176.1] 
In [64]:
slist[3] = 175.0
In [65]:
slist
Out[65]:
['Kim', 178.9, 'Park', 175.0, 'Lee', 176.1]
In [66]:
slist[2:4] = ['Paik', 180.0]
slist
Out[66]:
['Kim', 178.9, 'Paik', 180.0, 'Lee', 176.1]
In [67]:
slist.insert(4, "Hong") 
slist.insert(5, 168.1) 
slist
Out[67]:
['Kim', 178.9, 'Paik', 180.0, 'Hong', 168.1, 'Lee', 176.1]

LAB7-3 : 슬라이싱 실

7.8 항목을 삭제하는 방법은 여러가지가 있다

In [68]:
bts = [ "V", "J-Hope", "Suga", "Jungkook" ] 
bts.remove("Jungkook") 
bts 
Out[68]:
['V', 'J-Hope', 'Suga']
In [69]:
bts = ["V", "J-Hope", "Suga", "Jungkook"] 
last_member = bts.pop()   # ¸¶Áö¸· Ç׸ñ 'Jungkook'À» »èÁ¦ÇÏ°í ¹ÝȯÇÑ´Ù
last_member
Out[69]:
'Jungkook'
In [70]:
bts
Out[70]:
['V', 'J-Hope', 'Suga']
In [71]:
bts = [ "V", "J-Hope", "Suga", "Jungkook"] 
del bts[0]     # ¸®½ºÆ®ÀÇ Ã¹ Ç׸ñÀ» »èÁ¦ÇÏ´Â ¸í·É¾î
bts
Out[71]:
['J-Hope', 'Suga', 'Jungkook']

7.9 리스트의 객체의 생성과 참조라는 깊이있는 개념

In [72]:
alist = ['Kim', 'Park', 'Lee', 'Hong'] 
In [73]:
blist = alist 
blist[1] = 'Choi'  # blistÀÇ µÎ¹ø° Ç׸ñ°ªÀ» º¯°æÇÔ
alist 
Out[73]:
['Kim', 'Choi', 'Lee', 'Hong']
In [74]:
id(alist)
Out[74]:
2222263129864
In [75]:
id(blist) # À§ÀÇ °ª°ú µ¿ÀÏÇÔ
Out[75]:
2222263129864

7.10 리스트를 복제한 새로운 리스트 만들기

In [76]:
alist = ['Kim', 'Park', 'Lee', 'Hong'] 
blist = list(alist) 
id(alist)
Out[76]:
2222262994568
In [77]:
id(blist)     # blistÀÇ ¾ÆÀ̵ð´Â alistÀÇ ¾ÆÀ̵ð¿Í ´Ù¸¦ °ÍÀÌ´Ù.
Out[77]:
2222263358664
In [78]:
blist = alist[:]      # ÀÌ·¸°Ô ÇÏ¿©µµ µÈ´Ù. 
id(alist)
Out[78]:
2222262994568
In [79]:
id(blist)     # blistÀÇ ¾ÆÀ̵ð´Â alistÀÇ ¾ÆÀ̵ð¿Í ´Ù¸¦ °ÍÀÌ´Ù.
Out[79]:
2222262994824
In [80]:
blist[0] = 'Song'
alist         # alistÀÇ º¹»çº» blist¸¦ °íÃÆÀ¸¹Ç·Î ¾Æ¹«·± º¯È­°¡ ¾ø´Ù
Out[80]:
['Kim', 'Park', 'Lee', 'Hong']
In [81]:
blist         # alistÀÇ º¹»çº»ÀÇ Ã¹ ¹ø° Ç׸ñÀÌ º¯°æµÊ
Out[81]:
['Song', 'Park', 'Lee', 'Hong']

7.11 리스트 탐색해보자

In [82]:
bts = [ "V", "J-Hope", "Suga", "Jungkook" ] 
bts.index("Suga") 
Out[82]:
2
In [83]:
if "Suga" in bts: 
    print(bts.index("Suga")) 
2
In [84]:
bts = ["V", "J-Hope", "Suga", "Jungkook" ] 
for member in bts: 
    print(member)
V
J-Hope
Suga
Jungkook

7.12 리스트를 크기에 따라 정렬해보자

In [85]:
numbers = [ 9, 6, 7, 1, 8, 4, 5, 3, 2 ]
numbers.sort()
print(numbers)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [86]:
numbers.sort(reverse=True) 
print(numbers) 
[9, 8, 7, 6, 5, 4, 3, 2, 1]
In [87]:
bts = [ "V", "J-Hope", "Suga", "Jungkook" ] 
bts.sort() 
print(bts)
['J-Hope', 'Jungkook', 'Suga', 'V']
In [88]:
numbers = [ 9, 6, 7, 1, 8, 4, 5, 3, 2 ]
new_list = sorted(numbers)
print(new_list)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [89]:
print(numbers)
[9, 6, 7, 1, 8, 4, 5, 3, 2]
In [90]:
numbers = [ 9, 6, 7, 1, 8, 4, 5, 3, 2 ]
new_list = sorted(numbers, reverse=True)
print(new_list)
[9, 8, 7, 6, 5, 4, 3, 2, 1]

도전문제

  • ´ÙÀ½ ÄÚµåÀÇ ½ÇÇà°á°ú¸¦ ¿¹»óÇØ º¸°í Á÷Á¢ ½ÇÇà½ÃÄѺ¸ÀÚ.
In [91]:
sorted("FADEAWAY")
Out[91]:
['A', 'A', 'A', 'D', 'E', 'F', 'W', 'Y']

LAB7-4 : 오늘의 명언을 골라주는 기능을 만들자

In [92]:
import random 
 
quotes = [] 
quotes.append("²ÞÀ» Áö³à¶ó. ±×·¯¸é ¾î·Á¿î Çö½ÇÀ» ÀÌ±æ ¼ö ÀÖ´Ù.") 
quotes.append("ºÐ³ë´Â ¹Ùº¸µéÀÇ °¡½¿¼Ó¿¡¼­¸¸ »ì¾Æ°£´Ù..") 
quotes.append("°í»ý ¾øÀÌ ¾òÀ» ¼ö ÀÖ´Â Áø½Ç·Î ±ÍÁßÇÑ °ÍÀº Çϳªµµ ¾ø´Ù.") 
quotes.append("»ç¶÷Àº »ç¶ûÇÒ ¶§ ´©±¸³ª ½ÃÀÎÀÌ µÈ´Ù.") 
quotes.append("½ÃÀÛÀÌ ¹ÝÀÌ´Ù.") 
 
print("############################") 
print("# ¿À´ÃÀÇ ¸í¾ð #") 
print("############################") 
print("") 
dailyQuote = random.choice(quotes) 
print(dailyQuote)
############################
# ¿À´ÃÀÇ ¸í¾ð #
############################

ºÐ³ë´Â ¹Ùº¸µéÀÇ °¡½¿¼Ó¿¡¼­¸¸ »ì¾Æ°£´Ù..

도전문제

  • "100 + 200"°ú °°Àº »ê¼ö ¹®Á¦¸¦ 10°³ ÀúÀåÇÏ°í ÀÖ´Â ¸®½ºÆ®¸¦ ÀÛ¼ºÇÏ°í ¿©±â¿¡¼­ ·£´ýÇÏ°Ô Çϳª¸¦ °ñ¶ó¼­ »ç¿ëÀÚ¿¡°Ô Á¦°øÇÏ´Â ÇÁ·Î±×·¥À» ÀÛ¼ºÇ϶ó. ´ÙÀ½°ú °°ÀÌ eval() ÇÔ¼ö¸¦ »ç¿ëÇÏ¸é ¹®ÀÚ¿­·Î ÀÌ·ç¾îÁø ÀÌ ¹®ÀåÀ» ÆÄÀ̽㠼ö½ÄÀ¸·Î Æò°¡ÇÏ¿© ¿¬»êÀ» ¼öÇàÇÏ´Â °ÍÀÌ °¡´ÉÇÏ´Ù.
In [93]:
eval("100 + 200")  # ¹®ÀÚ¿­À» ÆÄÀ̽㠹®ÀåÀ¸·Î Çؼ®ÇÏ¿© 100 + 200À» ¼öÇàÇÔ
Out[93]:
300

7.13 리스트 함축은 코드를 짧고 간결하게 만드는데 사용된다

In [94]:
[ x**2 for x in [1, 2, 3, 4, 5] ] 
Out[94]:
[1, 4, 9, 16, 25]
In [95]:
s = [] 
for x in [1, 2, 3, 4, 5]: 
    s.append(x**2)
In [96]:
[x for x in range(10)]# 0¿¡¼­ 9±îÁö ¼ýÀÚ¸¦ Æ÷ÇÔÇÏ´Â ¸®½ºÆ®
Out[96]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [97]:
[x * x for x in range(10)] # 0¿¡¼­ 9±îÁö ¼ýÀÚÀÇ Á¦°ö °ª
Out[97]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [98]:
st = 'Hello World'
[x.upper() for x in st]    # ¹®ÀÚ¿­ °¢°¢¿¡ ´ëÇØ upper() ¸Þ¼Òµå Àû¿ë
Out[98]:
['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']
In [99]:
a = ['welcome', 'to', 'the', 'python', 'world']
first_a = [ s[0].upper() for s in a]  # ù ¾ËÆĺª¿¡ ´ëÇÑ ´ë¹®ÀÚ º¯È¯
print(first_a)
['W', 'T', 'T', 'P', 'W']

7.14 조건이 붙는 리스트 함축표현도 가능하다

In [100]:
[x for x in range(10) if x % 2 == 0]
Out[100]:
[0, 2, 4, 6, 8]
In [101]:
[x**2 for x in range(10) if x % 2 == 0]  # Ãâ·Â½Ä¿¡ Á¦°öÀ» ÇÒ ¼ö ÀÖ´Ù
Out[101]:
[0, 4, 16, 36, 64]
In [102]:
s = ["Hello", "12345", "World", "67890"] 
numbers = [x for x in s if x.isdigit()] 
print(numbers)
['12345', '67890']
In [103]:
[int(x) for x in input('Á¤¼ö¸¦ ¿©·¯°³ ÀÔ·ÂÇϼ¼¿ä : ').split()]
Á¤¼ö¸¦ ¿©·¯°³ ÀÔ·ÂÇϼ¼¿ä : 10 20 30
Out[103]:
[10, 20, 30]
In [104]:
[int(x) for x in input('Á¤¼ö¸¦ ¿©·¯°³ ÀÔ·ÂÇϼ¼¿ä : ').split() if x.isdigit()]
Á¤¼ö¸¦ ¿©·¯°³ ÀÔ·ÂÇϼ¼¿ä : 20 30 40
Out[104]:
[20, 30, 40]
In [105]:
[(x, y) for x in [1, 2, 3] for y in [3, 1, 4]] 
Out[105]:
[(1, 3), (1, 1), (1, 4), (2, 3), (2, 1), (2, 4), (3, 3), (3, 1), (3, 4)]
In [106]:
[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
Out[106]:
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

7.15 한번 생성하면 그 값을 고칠 수 없는 자료형 : 튜플

In [107]:
colors = ("red", "green", "blue") 
colors 
Out[107]:
('red', 'green', 'blue')
In [108]:
numbers = (1, 2, 3, 4, 5 ) 
numbers 
Out[108]:
(1, 2, 3, 4, 5)
In [109]:
t1 = (1, 2, 3, 4, 5)
t1[0] = 100
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-109-614bcaadef71> in <module>
      1 t1 = (1, 2, 3, 4, 5)
----> 2 t1[0] = 100

TypeError: 'tuple' object does not support item assignment
In [110]:
t1 = (1, 2, 3, 4, 5)
t1[0]          # Æ©ÇÃÀÇ À妽Ì-¸®½ºÆ® Àε¦½Ì°ú µ¿ÀÏÇÑ ¹æ½Ä
Out[110]:
1
In [111]:
t1[1:4]        # Æ©ÇÃÀÇ ½½¶óÀÌ½Ì °á°ú·Î Æ©ÇÃÀ» ¹ÝȯÇÔ
Out[111]:
(2, 3, 4)
In [112]:
t2 = t1 + t1   # Æ©ÇÃÀÇ °áÇÕ ¿¬»ê
t2
Out[112]:
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

LAB7-5 ÇÔ¼ö´Â Æ©ÇÃÀ» µ¹·ÁÁÙ ¼ö ÀÖ´Ù

In [113]:
import math 
 
def calCircle(r): 
    # ¹ÝÁö¸§ÀÌ rÀÎ ¿øÀÇ ³ÐÀÌ¿Í µÑ·¹¸¦ µ¿½Ã¿¡ ¹ÝȯÇÏ´Â ÇÔ¼ö (area, circum) 
    area = math.pi * r * r 
    circum = 2 * math.pi * r 
    return area, circum    # Æ©ÇÃÀ» ¹ÝȯÇÔ
 
radius = float(input("¿øÀÇ ¹ÝÁö¸§À» ÀÔ·ÂÇϽÿÀ: ")) 
(a, c) = calCircle(radius) 
print("¿øÀÇ ³ÐÀÌ´Â "+str(a)+"ÀÌ°í ¿øÀÇ µÑ·¹´Â"+str(c)+"ÀÌ´Ù.")
¿øÀÇ ¹ÝÁö¸§À» ÀÔ·ÂÇϽÿÀ: 10
¿øÀÇ ³ÐÀÌ´Â 314.1592653589793ÀÌ°í ¿øÀÇ µÑ·¹´Â62.83185307179586ÀÌ´Ù.

LAB 7-6 : 도시의 이름과 인구를 튜플로 묶어보자

In [114]:
city_info = [('¼­¿ï', 9765), ('ºÎ»ê', 3441), ('ÀÎõ', 2954), 
             ('±¤ÁÖ', 1501), ('´ëÀü', 1531)]
In [115]:
max_pop = 0
min_pop = 999999999999999999
total_pop = 0

max_city = None
min_city = None

for city in city_info:
   total_pop += city[1]
   if city[1] > max_pop :
       max_pop = city[1]
       max_city = city
   if city[1] < min_pop :
       min_pop = city[1]
       min_city = city

print('ÃÖ´ëÀα¸: {0}, Àα¸: {1} õ¸í'.format(max_city[0], max_city[1]))
print('ÃÖ¼ÒÀα¸: {0}, Àα¸: {1} õ¸í'.format(min_city[0], min_city[1]))
print('¸®½ºÆ® µµ½Ã Æò±Õ Àα¸: {0} õ¸í'.format(total_pop / len(city_info)) )
ÃÖ´ëÀα¸: ¼­¿ï, Àα¸: 9765 õ¸í
ÃÖ¼ÒÀα¸: ±¤ÁÖ, Àα¸: 1501 õ¸í
¸®½ºÆ® µµ½Ã Æò±Õ Àα¸: 3838.4 õ¸í

7.16 클래스와 객체가 무엇인가?

In [116]:
animals = ['lion', 'tiger', 'cat', 'dog']
animals.sort()     # animals ¸®½ºÆ®ÀÇ ³»ºÎ ¹®ÀÚ¿­À» ¾ËÆĺª ¼øÀ¸·Î Á¤·ÄÇÑ´Ù
animals
Out[116]:
['cat', 'dog', 'lion', 'tiger']
In [117]:
animals.append('rabbit')  # animals ¸®½ºÆ®¿¡ »õ ¿ø¼Ò¸¦ Ãß°¡ÇÑ´Ù
animals
Out[117]:
['cat', 'dog', 'lion', 'tiger', 'rabbit']
In [118]:
animals.reverse()         # animals ¸®½ºÆ®¸¦ ¿ø·¡ ¿ø¼ÒÀÇ ¿ª¼øÀ¸·Î Àç¹è¿­ÇÑ´Ù
animals
Out[118]:
['rabbit', 'tiger', 'lion', 'dog', 'cat']