상세 컨텐츠

본문 제목

열거의 고급형 기초 지식

Python

by techbard 2015. 7. 9. 17:10

본문

반응형
  • List comprehension

# 열거형을 순회하면서 무언가를 한다.

fs = ['apple', 'pear', 'grape']

fs_lines = []


for f in fs:

fs_lines.append(f + '\n')


print(fs_lines)


결과)

['apple\n', 'pear\n', 'grape\n']


# 열거형을 인덱스 번호로 접근한다.

l = [1, 2, 3]


for i in range(len(l)):

    print(l[i])


결과)

1

2

3


# 리스트 컴프리헨션을 사용한다.

fs = ['apple', 'pear', 'grape']

fs_lines = []


fs_lines = [f + '\n' for f in fs]


print(fs_lines)


결과)

['apple\n', 'pear\n', 'grape\n']


# 리스트 컴프리헨션과 조건필터의 사용

fs = ['apple', 'pear', 'grape']

fs_lines = []


fs_lines = [f + '\n' for f in fs if 'l' in f]


print(fs_lines)


결과)

['apple\n']


# 리스트 컴프리헨션과 다중 조건 필터의 사용

n = range(1, 11)


even = [x for x in n if x % 2 == 0]


evenOverFour1 = [x for x in n if x % 2 == 0 and x > 4]

evenOverFour2 = [x for x in n if x % 2 == 0 if x > 4]


print(even)

print(evenOverFour1)

print(evenOverFour2)


결과)

[2, 4, 6, 8, 10]

[6, 8, 10]

[6, 8, 10]


# 중첩 리스트 컴프리헨션과 다중 조건 필터의 사용

m = [[1,2], [3,4], [5,6]]


filtered = [[x for x in row if x % 3 == 0] for row in m if sum(row) >= 10]


print(filtered)


결과)

[[6]]


# 다중표현식 리스트 컴프리헨션의 사용 (n by n 조합)

fs = ['apple', 'pear', 'grape']

cs = ['pie', 'cake', 'juice']

fscs = []


fscs = [f + ' ' + c for f in fs for c in cs]


print(fscs)


결과)

['apple pie', 'apple cake', 'apple juice', 'pear pie', 'pear cake', 'pear juice', 'grape pie', 'grape cake', 'grape juice']


# 다중표현식 리스트 컴프리헨션의 사용 (리스트 합치기)

m = [[1,2], [3,4], [5,6]]


f = [x for row in m for x in row]


print(f)


결과)

[1, 2, 3, 4, 5, 6]


# 중첩 리스트 컴프리헨션의 사용

m = [[1,2], [3,4], [5,6]]


sq = [[x**2 for x in row] for row in m]


print(sq)


결과)

[[1, 4], [9, 16], [25, 36]]


# 열거형의 flattenning

m = [

    [[1,2], [3,4]],

    [[5,6], [7,8]]

]


flat = []


for sl1 in m:

    for sl2 in sl1:

        flat.extend(sl2)


print(flat)


결과)

[1, 2, 3, 4, 5, 6, 7, 8]


# 중첩 루프를 리스트 컴프리헨션으로 구현 - for loop

a = [1, 2, 3]

b = [4, 5, 6]

c = []


for x in a:

for y in b:

if x is not y:

c.append((x, y))


print(c)


결과)

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]


# 중첩 루프를 리스트 컴프리헨션으로 구현 - list comprehension

a = [1, 2, 3]

b = [4, 5, 6]

c = []


c = [(x,y) for x in a for y in b if x != y]


print(c)


결과)

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]


# 열거형의 인덱스 튜플 생성

f = ['banana', 'apple', 'lime']


print(list(enumerate(f)))


결과)

[(0, 'banana'), (1, 'apple'), (2, 'lime')]

  • 사전 컴프리헨션

# 사전 컴프리헨션

d = {

    'apple': 1,

    'banana': 2,

    'lemon': 3

    }


new_d = {fruitName: count + 1 for fruitName, count in d.items()}


print(new_d)


결과)

{'apple': 2, 'banana': 3, 'lemon': 4}

  • Generator 표현식

# 리스트 컴프리헨션 대신에 제너레이터 표현식을 사용하면 적은 메모리를 가지고 같은 일을 한다. 요청할 때마다 하나씩 생성한다.

# 제너레이터 표현식 생성하기 (리스트 컴프리헨션에서는 대괄호를 사용하지만 제너레이터 생성에는 소괄호를 사용하는 점에 주의)

fs = ['apple', 'pear', 'grape']


l_lines = (f + "\n" for f in fs)


print(type(l_lines))


결과)

<class 'generator'>


# 제너레이터에서 하나씩 가져오기 (리스트를 사용하면 하나의 거대한 고정 리스트를 만든 후 진행하지만, 제너레이터는 하나씩만 생성하고 하나씩 작업이 가능하다.)

fs = ['apple', 'pear', 'grape']


l_lines = (f + "\n" for f in fs)


print(next(l_lines))

print(next(l_lines))

print(next(l_lines))


결과)

apple


pear


grape


# Python 3.x에서는 next 메쏘드 이름이 바뀐 것 같다.

fs = ['apple', 'pear', 'grape']


l_lines = (f + "\n" for f in fs)


print(l_lines.__next__())

print(l_lines.__next__())

print(l_lines.__next__())


결과)

apple


pear


grape

  • Generator 함수

# 함수 안에서는 yield 구문을 통해 요청할 때마다 하나씩 생성한다.

fs = ['apple', 'pear', 'grape']


def one_per_line():

for f in fs:

yield f + "\n"


g = one_per_line()


print(type(g))


결과)

<class 'generator'>


# for - in 구문에서 묵시적으로 next()를 호출하여 사용할 수 있다.

fs = ['apple', 'pear', 'grape']


def one_per_line():

for f in fs:

yield f + "\n"


for l in one_per_line():

print(l)


결과)

apple


pear


grape


# Generator 예제 2 - 제너레이터 생성

def displayEven(end):

    for i in range(0, end, 2):

        yield i


g = displayEven(3)


print(type(g))


결과)

<class 'generator'>


Generator 예제 2 - next() 키워드로 결과 생성

def displayEven(end):

    for i in range(0, end, 2):

        yield i


g = displayEven(3)


print(next(g))

print(next(g))


결과)

0

2


Generator 예제 2 - StopIteration 에러를 피해 유효한 값만 생성하는 방법

def displayEven(end):

    for i in range(0, end, 2):

        yield i


g = displayEven(3)


for i in displayEven(3):

    print(i)


결과)

0

2

  • Iterator

# Iterable 객체에서 iterator를 생성한다.

iterator = iter('ab')


print(next(iterator))

print(next(iterator))


결과)

a

b


# next() 함수에 인자로 StopIteration 에러 없이 기본값을 생성할 수 있다.

iterator = iter('ab')


print(next(iterator, 'z'))

print(next(iterator, 'z'))

print(next(iterator, 'z'))

print(next(iterator, 'z'))


결과)

a

b

z

z

  • zip 내장함수로 로직 단순화하기

# 리스트 요소중 길이가 가장 긴 것 출력하기

names = ['apple', 'banana', 'pear']

maxName = names[0]


for n in names[1:]:

    if len(maxName) < len(n):

        maxName = n


print(maxName)


결과)

banana


# zip() 내장함수를 이용해 로직 단순화하기

names = ['apple', 'banana', 'pear']

lengths = [len(n) for n in names]


longestName = None

maxLengths = 0


for name, count in zip(names, lengths):

    if count > maxLengths:

        longestName = name

        maxLengths = count


print(longestName)


결과)

banana

  • reduce() 내장함수

# 누적식으로 함수의 인자로 넣음 - string 결합

from functools import reduce


a = reduce(lambda x, y: x + ' ' + y, 'newworld')

print(str(a))


결과)

n e w w o r l d


# 누적식으로 함수의 인자로 넣음 - 정수계산

from functools import reduce


a = reduce(lambda x, y: x + y, range(1, 11))

print(a)


결과)

55


반응형

관련글 더보기

댓글 영역