A A
[Data Mining] Crash_Course in Python Part.2

The Not-So-Basics

Sorting

x = [4,1,2,3]
y = sorted(x)    # is [1,2,3,4], x is unchanged
x.sort()         # now x is [1,2,3,4]
# sort the list by absolute value from largest to smallest
x = sorted([-4,1,-2,3], key=abs, reverse=True) # is [-4,3,-2,1]
# sort the words and counts from highest count to lowest
wc = sorted(word_counts.items(),
            key=lambda x: x[1], # x[1] λ‘λ²ˆμ§Έ 값을 κΈ°μ€€μœΌλ‘œ μ •λ ¬
            reverse=True)

wc
# [('I', 2), ('am', 1), ('a', 1), ('boy', 1), ('love', 1), ('you', 1)]
  • x λ¦¬μŠ€νŠΈλŠ” μ ˆλŒ“κ°’μ— 따라 λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ μ •λ ¬λ©λ‹ˆλ‹€.
    • sorted() ν•¨μˆ˜λŠ” μž…λ ₯ 리슀트λ₯Ό μ •λ ¬ν•©λ‹ˆλ‹€.
    • key=abs μΈμžλŠ” μ •λ ¬ ν‚€λ₯Ό μ ˆλŒ“κ°’μœΌλ‘œ μ„€μ •ν•©λ‹ˆλ‹€.
    • reverse=True μΈμžλŠ” λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ 정렬됨을 λ‚˜νƒ€λƒ…λ‹ˆλ‹€.
  • wcλŠ” 단어 및 ν•΄λ‹Ή 카운트λ₯Ό 가진 λ”•μ…”λ„ˆλ¦¬λ₯Ό κ°€μž₯ λ§Žμ€ μΉ΄μš΄νŠΈλΆ€ν„° κ°€μž₯ 적은 카운트둜 μ •λ ¬λ©λ‹ˆλ‹€.
    • sorted() ν•¨μˆ˜μ˜ key λ§€κ°œλ³€μˆ˜λŠ” 각 μš”μ†Œμ— λŒ€ν•΄ μ μš©λ˜λŠ” ν•¨μˆ˜λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
    • μ—¬κΈ°μ„œλŠ” λžŒλ‹€ ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ μš”μ†Œμ˜ 두 번째 κ°’(카운트), λ‹¨μ–΄μ˜ μΆœμ—° λΉˆλ„λ₯Ό κΈ°μ€€μœΌλ‘œ μ •λ ¬ν•©λ‹ˆλ‹€.
    • reverse=True μΈμžλŠ” λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ 정렬됨을 λ‚˜νƒ€λƒ…λ‹ˆλ‹€.
word_counts.items()λŠ” λ”•μ…”λ„ˆλ¦¬μ˜ 각 ν•­λͺ©μ„ νŠœν”Œλ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.
예λ₯Ό λ“€μ–΄, { 'I': 2, 'am': 1, 'a': 1 }μ΄λΌλŠ” λ”•μ…”λ„ˆλ¦¬κ°€ μžˆλ‹€λ©΄, items() λ©”μ†Œλ“œλŠ” ('I', 2), ('am', 1), ('a', 1)κ³Ό 같은 νŠœν”Œλ“€μ˜ 리슀트λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
sorted() ν•¨μˆ˜μ— μ˜ν•΄ 두 번째 μš”μ†Œ(즉, νŠœν”Œμ˜ 두 번째 κ°’)λ₯Ό κΈ°μ€€μœΌλ‘œ λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ μ •λ ¬λ©λ‹ˆλ‹€.
λ”°λΌμ„œ word_counts.items()κ°€ νŠœν”Œλ“€μ˜ 리슀트λ₯Ό λ°˜ν™˜ν•˜λ―€λ‘œ 두 번째 값은 ν•΄λ‹Ή λ‹¨μ–΄μ˜ μΆœν˜„ λΉˆλ„λ₯Ό λ‚˜νƒ€λƒ…λ‹ˆλ‹€.
x[0]: ‘단어’, x[1]: ‘숫자’
  • 단어와 ν•΄λ‹Ή 카운트λ₯Ό κ°€μž₯ λ§Žμ€ μΉ΄μš΄νŠΈλΆ€ν„° κ°€μž₯ 적은 카운트둜 μ •λ ¬ν•©λ‹ˆλ‹€.

List Comprehensions

  • νŠΉμ • μš”μ†Œλ§Œμ„ μ„ νƒν•˜κ±°λ‚˜ μš”μ†Œλ₯Ό λ³€ν™˜ν•˜κ±°λ‚˜ λ‘˜ λ‹€λ₯Ό μ„ νƒν•˜μ—¬ λͺ©λ‘μ„ λ‹€λ₯Έ λͺ©λ‘μœΌλ‘œ λ³€ν™˜ν•˜κ³ μž ν•  κ²ƒμž…λ‹ˆλ‹€.
  • λͺ©λ‘μ˜ 포괄성은 νŒŒμ΄ν† λ‹‰ 방식에 μ˜ν•΄ κ²°μ •λ©λ‹ˆλ‹€.
  • κ°€λŠ₯ν•˜λ©΄ 항상 List Comprehensionsλ₯Ό μ‚¬μš©ν•©λ‹ˆλ‹€.
even_numbers = [x for x in range(5) if x % 2 == 0]  # [0, 2, 4], 0 ~ 4 사이쀑
squares      = [x * x for x in range(5)]            # [0, 1, 4, 9, 16]
even_squares = [x * x for x in even_numbers]        # [0, 4, 16]
  • λ§ˆμ°¬κ°€μ§€λ‘œ List을 Dictionary λ˜λŠ” Set으둜 λ³€ν™˜ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
square_dict = { x : x * x for x in range(5) }  # { 0:0, 1:1, 2:4, 3:9, 4:16 }
square_set = { x * x for x in [1, -1] }        # { 1 } # set은 쀑볡 μš”μ†Œ 포함 X
  • λ³€μˆ˜λ‘œ 밑쀄을 μ‚¬μš©ν•˜λŠ” 것이 μΌλ°˜μ μž…λ‹ˆλ‹€.
    • ‘_’은 값이 ν•„μš”ν•˜μ§€ μ•Šμ„λ•Œ μ‚¬μš©. even_numbers = [0, 2, 4] → Zeros List: [0, 0, 0]'
zeroes = [0 for _ in even_numbers]    # has the same length as even_numbers
  • List Comprehension λ‹€μŒκ³Ό 같은 μ—¬λŸ¬ 가지 μ΄μœ κ°€ 포함될 수 μžˆμŠ΅λ‹ˆλ‹€.
pairs = [(x, y)
         for x in range(10)
         for y in range(10)] # 100 pairs (0,0) (0,1) ... (9,8), (9,9)
  • 컴퓨터 μ‚¬μš©μ΄ μ‰¬μš΄ 거리 ν–‰λ ¬, λ‚˜μ€‘μ—λŠ” μ΄μ „μ˜ κ²°κ³Όλ₯Ό μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
increasing_pairs = [(x, y)
                    for x in range(10)
                    for y in range(x + 1, 10)]
                    
# [(0,1), (0,2), (0,3) ... (8, 9)]
  • 0λΆ€ν„° 9κΉŒμ§€μΈ λͺ¨λ“  숫자 μŒμ„ μƒμ„±ν•©λ‹ˆλ‹€.
  • 이 μŒλ“€μ€ 첫 번째 μš”μ†Œκ°€ 두 번째 μš”μ†Œλ³΄λ‹€ μž‘μ€ μ¦κ°€ν•˜λŠ” μˆœμ„œμŒμž…λ‹ˆλ‹€.

Generators & Iterators

  • List의 λ¬Έμ œμ μ€ Listκ°€ μ‰½κ²Œ 맀우 컀질 수 μžˆλ‹€λŠ” κ²ƒμž…λ‹ˆλ‹€.
  • range(1000000)λŠ” μ‹€μ œ 100만 개의 μ›μ†Œ λͺ©λ‘μ„ λ§Œλ“­λ‹ˆλ‹€.
  • λ§Œμ•½ 당신이 ν•œ λ²ˆμ— ν•˜λ‚˜μ”©λ§Œ 닀루면 λœλ‹€λ©΄, 이것은 μ—„μ²­λ‚œ λΉ„νš¨μœ¨μ„±μ˜ μ›μ²œ(λ˜λŠ” λ©”λͺ¨λ¦¬ λΆ€μ‘±μ˜ 원인)이 될 수 μžˆμŠ΅λ‹ˆλ‹€.
  • λ§Œμ•½ 당신이 잠재적으둜 처음 λͺ‡ 개의 κ°’λ§Œ ν•„μš”ν•˜λ‹€λ©΄, 그것듀을 λͺ¨λ‘ κ³„μ‚°ν•˜λŠ” 것은 λ‚­λΉ„μž…λ‹ˆλ‹€.
  • GeneratorλŠ” μ‚¬μš©μžκ°€ λ°˜λ³΅ν•  수 μžˆμ§€λ§Œ(우리의 경우, 일반적으둜 에 μ‚¬μš©ν•©λ‹ˆλ‹€) ν•„μš”μ— 따라 값이 μƒμ„±λ˜λŠ” 것(lazily)μž…λ‹ˆλ‹€.
  • Generatorλ₯Ό λ§Œλ“œλŠ” ν•œ 가지 방법은 ν•¨μˆ˜μ™€ yield μ—°μ‚°μžλ₯Ό μ‚¬μš©ν•˜λŠ” κ²ƒμž…λ‹ˆλ‹€:
def lazy_range(n):
    """a lazy version of range"""
    i = 0
    while i < n:
        yield i
        i += 1
# The following loop will consume the yield ed values one at a time until none are left:
for i in lazy_range(10):
    print(i)
0
1
2
3
4
5
6
7
8
9
# The following loop will consume the yield ed values one at a time until none are left:
for i in lazy_range(10000):
    if i == 3: break
    print(i)
0
1
2
t = lazy_range(3)
next(t)
next(t)
next(t)
#next(t)

# 2
def lazy_inf_range():
    i = 0
    while True:
        yield i
        i += 1

t = lazy_inf_range()
next(t)
next(t)
next(t)

# 2
  • Generatorλ₯Ό λ§Œλ“œλŠ” 두 번째 방법은 κ΄„ν˜Έ μ•ˆμœΌλ‘œ 포μž₯된 comprehension에 μ‚¬μš©ν•˜λŠ” κ²ƒμž…λ‹ˆλ‹€:
lazy_evens_below_20 = (i for i in lazy_range(20) if i % 2 == 0)
lazy_evens_below_20

# <generator object <genexpr> at 0x7cce6849c4a0>

Randomness

  • λ‚œμˆ˜λ₯Ό μƒμ„±ν•˜κΈ° μœ„ν•΄, μš°λ¦¬λŠ” λ‚œμˆ˜ λͺ¨λ“ˆμ„ μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
  • random.random()λŠ” 0μ—μ„œ 1 μ‚¬μ΄μ˜ 숫자λ₯Ό κ· μΌν•˜κ²Œ μƒμ„±ν•©λ‹ˆλ‹€.
import random

four_uniform_randoms = [random.random() for _ in range(4)]
four_uniform_randoms
[0.15001730378211198,
 0.047689363188983425,
 0.4438845111618783,
 0.8064273339306516]
  • reproducible κ°€λŠ₯ν•œ κ²°κ³Όλ₯Ό μ–»μœΌλ €λŠ” 경우.
random.seed(10)
print(random.random())
random.seed(10)
print(random.random())
0.5714025946899135
0.5714025946899135
  • random.randrangeλŠ” 1 λ˜λŠ” 2개의 인수λ₯Ό μ‚¬μš©ν•˜κ³  ν•΄λ‹Ή λ²”μœ„ ()μ—μ„œ μž„μ˜λ‘œ μ„ νƒν•œ μš”μ†Œλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
random.randrange(10)      # choose randomly from range(10) = [0, 1, ..., 9]
random.randrange(3, 6)    # choose randomly from range(3, 6) = [3, 4, 5]
  • random.shuffleλŠ” λͺ©λ‘μ˜ μš”μ†Œλ₯Ό μž„μ˜λ‘œ μž¬μ •λ ¬ν•©λ‹ˆλ‹€:
up_to_ten = list(range(10))
random.shuffle(up_to_ten)
print(up_to_ten)

# 4, 5, 8, 1, 2, 6, 7, 3, 0, 9]
  • λͺ©λ‘μ—μ„œ ν•œ μš”μ†Œλ₯Ό μž„μ˜λ‘œ μ„ νƒν•˜λŠ” λ°©λ²•μž…λ‹ˆλ‹€.
my_best_friend = random.choice(["Alice", "Bob", "Charlie"])
  • λŒ€μ²΄ν•˜μ§€ μ•Šκ³  μ›μ†Œ ν‘œλ³Έμ„ μž„μ˜λ‘œ μ„ νƒν•˜λŠ” λ°©λ²•μž…λ‹ˆλ‹€. (즉, μ€‘λ³΅λ˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€)
lottery_numbers = range(60)
winning_numbers = random.sample(lottery_numbers, 6)
  • λŒ€μ²΄ μš”μ†Œ ν‘œλ³Έμ„ μ„ νƒν•˜λŠ” λ°©λ²•μž…λ‹ˆλ‹€.(즉, 쀑볡을 ν—ˆμš©ν•©λ‹ˆλ‹€)
four_with_replacement = [random.choice(range(10)) for _ in range(4)]
four_with_replacement

# [2, 9, 5, 6]
  • random.choice(range(10))λŠ” 0λΆ€ν„° 9κΉŒμ§€μ˜ 숫자 μ€‘μ—μ„œ ν•˜λ‚˜λ₯Ό λ¬΄μž‘μœ„λ‘œ μ„ νƒν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
  • 이λ₯Ό 리슀트 μ»΄ν”„λ¦¬ν—¨μ…˜ 으둜 4번 λ°˜λ³΅ν•˜μ—¬ 리슀트λ₯Ό 생성. 쀑볡을 ν—ˆμš©ν•©λ‹ˆλ‹€. λ¬΄μž‘μœ„λ‘œ μ„ νƒλœ 0λΆ€ν„° 9κΉŒμ§€μ˜ μˆ«μžκ°€ 4개 포함.

Regular Expressions

  • μ •κ·œ ν‘œν˜„μ‹μ€ ν…μŠ€νŠΈλ₯Ό κ²€μƒ‰ν•˜λŠ” 방법을 μ œκ³΅ν•©λ‹ˆλ‹€.
  • 그것듀은 믿을 수 없을 μ •λ„λ‘œ μœ μš©ν•˜μ§€λ§Œ λ˜ν•œ κ½€ λ³΅μž‘ν•΄μ„œ 그것듀에 λŒ€ν•œ 전체 책이 μžˆμŠ΅λ‹ˆλ‹€.
import re

# μ •κ·œ ν‘œν˜„μ‹μ„ μ‚¬μš©ν•˜μ—¬ λ‹€μ–‘ν•œ λ¬Έμžμ—΄ μž‘μ—…μ„ μˆ˜ν–‰ν•˜κ³ , 각 μž‘μ—…μ˜ κ²°κ³Όλ₯Ό κ²€μ‚¬ν•©λ‹ˆλ‹€.
# λͺ¨λ“  쑰건이 참일 경우 Trueλ₯Ό 좜λ ₯ν•©λ‹ˆλ‹€.

print(all([
    not re.match("a", "cat"),                # "cat" λ¬Έμžμ—΄μ€ "a"둜 μ‹œμž‘ν•˜μ§€ μ•ŠμŒ
    re.search("a", "cat"),                    # "cat" λ¬Έμžμ—΄μ— "a"κ°€ ν¬ν•¨λ˜μ–΄ 있음
    not re.search("c", "dog"),                # "dog" λ¬Έμžμ—΄μ— "c"κ°€ ν¬ν•¨λ˜μ–΄ μžˆμ§€ μ•ŠμŒ
    3 == len(re.split("[ab]", "carbs")),    # "carbs" λ¬Έμžμ—΄μ„ "[ab]"λ₯Ό κΈ°μ€€μœΌλ‘œ λΆ„ν• ν•˜λ©΄ ['c', 'r', 's']κ°€ 되며, 길이가 3μž„
    "R-D-" == re.sub("[0-9]", "-", "R2D2")    # "R2D2" λ¬Έμžμ—΄μ—μ„œ 숫자λ₯Ό "-"둜 λŒ€μ²΄ν•˜λ©΄ "R-D-"κ°€ 됨
]))    # 좜λ ₯ κ²°κ³ΌλŠ” True


Object-Oriented Programming

# κ΄€λ‘€μ μœΌλ‘œ, ν΄λž˜μŠ€λŠ” PascalCase 이름을 μ‚¬μš©ν•©λ‹ˆλ‹€.
class Set:
    # 이것듀은 멀버 ν•¨μˆ˜μž…λ‹ˆλ‹€.
    # 각 ν•¨μˆ˜λŠ” "self"λΌλŠ” 첫 번째 λ§€κ°œλ³€μˆ˜λ₯Ό κ°€μ Έμ•Ό ν•©λ‹ˆλ‹€(또 λ‹€λ₯Έ κ΄€λ‘€μž…λ‹ˆλ‹€).
    # 이 "self"λŠ” μ‚¬μš©λ˜λŠ” νŠΉμ • Set 객체λ₯Ό κ°€λ¦¬ν‚΅λ‹ˆλ‹€.

    def __init__(self, values=None):
        """이것은 μƒμ„±μžμž…λ‹ˆλ‹€.
        μƒˆλ‘œμš΄ Set을 λ§Œλ“€ λ•Œ ν˜ΈμΆœλ©λ‹ˆλ‹€.
        λ‹€μŒκ³Ό 같이 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
        s1 = Set()          # 빈 집합
        s2 = Set([1,2,2,3]) # κ°’μœΌλ‘œ μ΄ˆκΈ°ν™”"""

        self.dict = {}  # 각 Set μΈμŠ€ν„΄μŠ€λ§ˆλ‹€ κ³ μœ ν•œ dict 속성이 μžˆμŠ΅λ‹ˆλ‹€.
                        # 이 속성은 멀버십을 μΆ”μ ν•˜λŠ” 데 μ‚¬μš©λ©λ‹ˆλ‹€.
        if values is not None:
            for value in values:
                self.add(value)

    def __repr__(self):
        """이것은 Set 객체의 λ¬Έμžμ—΄ ν‘œν˜„μž…λ‹ˆλ‹€.
        Python ν”„λ‘¬ν”„νŠΈμ—μ„œ μž…λ ₯ν•˜κ±°λ‚˜ str()에 μ „λ‹¬ν•˜λ©΄ μ‚¬μš©λ©λ‹ˆλ‹€."""
        return "Set: " + str(self.dict.keys())

    # 각 μš”μ†Œμ˜ 멀버십은 self.dict의 ν‚€λ‘œ ν‘œμ‹œλ©λ‹ˆλ‹€.
    def add(self, value):
        self.dict[value] = True

    # 값이 집합에 μžˆλŠ”μ§€ μ—¬λΆ€λŠ” μ‚¬μ „μ˜ ν‚€λ‘œ νŒλ³„λ©λ‹ˆλ‹€.
    def contains(self, value):
        return value in self.dict

    def remove(self, value):
        del self.dict[value]

s = Set([1,2,3])
s.add(4)
print(s.contains(4))    # True
s.remove(3)
print(s.contains(3))    # False

Function Tools

  • ν•¨μˆ˜λ₯Ό 전달할 λ•Œ μƒˆ ν•¨μˆ˜λ₯Ό λ§Œλ“€κΈ° μœ„ν•΄ λΆ€λΆ„μ μœΌλ‘œ (λ˜λŠ” 카레) ν•¨μˆ˜λ₯Ό μ μš©ν•˜κ³  싢을 λ•Œκ°€ μžˆμŠ΅λ‹ˆλ‹€
def exp(base, power):
    return base ** power

def two_to_the(power):
    return exp(2, power)
    
two_to_the(3)

# 8
  • functools.partial을 μ‚¬μš©ν•˜λŠ” 것은 λ‹€λ₯Έ μ ‘κ·Ό 방식
from functools import partial

two_to_the = partial(exp, 2)     # is now a function of one variable
print(two_to_the(3))             # 8

square_of = partial(exp, power=2)
print(square_of(3))    # 9
  • λ˜ν•œ map, reduce 및 filterλ₯Ό μ‚¬μš©ν•˜μ—¬ 이해λ₯Ό λ‚˜μ—΄ν•˜λŠ” κΈ°λŠ₯적 λŒ€μ•ˆμ„ μ œκ³΅ν•˜κΈ°λ„ ν•©λ‹ˆλ‹€:
  • 항상 map μ‚¬μš©ν•˜κ³  κ°€λŠ₯ν•˜λ©΄ reduceν•˜κ³  filteringν•©λ‹ˆλ‹€.

Map

def double(x):
    return 2 * x

xs = [1, 2, 3, 4]

# 리슀트 μ»΄ν”„λ¦¬ν—¨μ…˜μ„ μ‚¬μš©ν•˜μ—¬ 각 μš”μ†Œλ₯Ό 두 배둜 λ§Œλ“­λ‹ˆλ‹€.
twice_xs = [double(x) for x in xs]

# map ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ 각 μš”μ†Œλ₯Ό 두 배둜 λ§Œλ“­λ‹ˆλ‹€.
twice_xs = map(double, xs)

# partial ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ map ν•¨μˆ˜μ— double ν•¨μˆ˜λ₯Ό μ μš©ν•©λ‹ˆλ‹€.
list_doubler = partial(map, double)
# list_doublerλ₯Ό μ‚¬μš©ν•˜μ—¬ xs의 각 μš”μ†Œλ₯Ό 두 배둜 λ§Œλ“­λ‹ˆλ‹€.
twice_xs = list_doubler(xs)

def multiply(x, y): return x * y

products = map(multiply, [1, 2], [4, 5])    # [1 * 4, 2 * 5] = [4, 10]
list(products)

# [4,10]
def multiply(x, y, z): return x * y * z

products = map(multiply, [1, 2], [4, 5], [10, 20])    # [1 * 4 * 10, 2 * 5 * 20]
list(products)

# [40, 200]

Filter

def is_even(x):
    """xκ°€ 짝수이면 True, ν™€μˆ˜μ΄λ©΄ Falseλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€."""
    return x % 2 == 0

xs = [1, 2, 3, 4]

# 리슀트 μ»΄ν”„λ¦¬ν—¨μ…˜μ„ μ‚¬μš©ν•˜μ—¬ 짝수만 ν•„ν„°λ§ν•©λ‹ˆλ‹€.
x_evens = [x for x in xs if is_even(x)]
print(x_evens)

# filter ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ 짝수만 ν•„ν„°λ§ν•©λ‹ˆλ‹€.
x_evens = filter(is_even, xs)
print(list(x_evens))

# partial ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ filter ν•¨μˆ˜μ— is_even ν•¨μˆ˜λ₯Ό μ μš©ν•©λ‹ˆλ‹€.
list_evener = partial(filter, is_even)
# list_evenerλ₯Ό μ‚¬μš©ν•˜μ—¬ xsμ—μ„œ 짝수만 ν•„ν„°λ§ν•©λ‹ˆλ‹€.
x_evens = list_evener(xs)
print(list(x_evens))
[2, 4]
[2, 4]

Reduce

def multiply(x, y): return x * y

xs = [1,2,3]
x_product = reduce(multiply, xs)
print(x_product)
list_product = partial(reduce, multiply)
x_product = list_product(xs)
print(x_product)
6
6

Enumerate

  • λͺ©λ‘μ—μ„œ λ°˜λ³΅ν•˜κ³  ν•΄λ‹Ή μš”μ†Œμ™€ 인덱슀λ₯Ό λͺ¨λ‘ μ‚¬μš©ν•˜λ €λ©΄ λ‹€μŒκ³Ό 같이 ν•˜λ©΄ λ©λ‹ˆλ‹€.
documents = ["I", "am", "a", "boy"]
# not Pythonic
for i in range(len(documents)):
    document = documents[i]
    print(i, document)

# also not Pythonic
i = 0
for document in documents:
    print(i, document)
    i += 1
0 I
1 am
2 a
3 boy
0 I
1 am
2 a
3 boy
  • Pythonic solution은 μ—΄κ±°ν˜•μœΌλ‘œ νŠœν”Œ(인덱슀, μš”μ†Œ)을 μƒμ„±ν•©λ‹ˆλ‹€:
for i, document in enumerate(documents):
    print(i, document)
0 I
1 am
2 a
3 boy
for i in range(len(documents)): print(i)    # not Pythonic

for i, _ in enumerate(documents): print(i)  # Pythonic
0
1
2
3
0
1
2
3

Zip & Unzip

  • λ‘˜ μ΄μƒμ˜ λͺ©λ‘μ„ ν•¨κ»˜ μ••μΆ•ν•©λ‹ˆλ‹€.
  • zip은 μ—¬λŸ¬ λͺ©λ‘μ„ ν•΄λ‹Ή μš”μ†Œμ˜ νŠœν”Œ 단일 λͺ©λ‘μœΌλ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€:
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
list(zip(list1, list2))        # is [('a', 1), ('b', 2), ('c', 3)]
  • μ΄μƒν•œ μ†μž„μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ Listλ₯Ό "Unzip"ν•  μˆ˜λ„ μžˆμŠ΅λ‹ˆλ‹€:
pairs = [('a', 1), ('b', 2), ('c', 3)]
letters, numbers = zip(*pairs)
print(letters, numbers)

# ('a', 'b', 'c') (1, 2, 3)
pairs = [('a', 1), ('b', 2), ('c', 3)]
letters, numbers = zip(('a', 1), ('b', 2), ('c', 3))
print(letters, numbers)

# ('a', 'b', 'c') (1, 2, 3)