Create TOC

2006년 11월 21일

Python/list 합치는 여러가지 방법

코드

#!/usr/bin/python
# -*- coding: utf-8 -*-

SRCLIST = range(1, 10)

# map을 이용하는 방법
print map(None, SRCLIST[:-1], SRCLIST[1:])

# built-in zip() 을 사용하는 방법
print zip(SRCLIST, SRCLIST[1:])

# itertools를 사용하는 방법
from itertools import izip, islice
print [(x, y) for x, y in izip(SRCLIST, islice(SRCLIST, 1, None))]

# generator를 사용하는 방법
def intervals(it):
    it = iter(it)
    st = it.next()
    for en in it:
        yield (st, en)
        st = en

print [interval for interval in intervals(SRCLIST)]

결과

[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]