2014-07-10 4 views
1

소스 목록을 반복하여 목록을 작성하고 있습니다. 특정 값을 발견하면 목록에서 다음 항목을 건너 뜁니다.for 루프에서 목록 항목을 건너 뛰십시오.

아래 process_things 함수를 작성하는 더 좋은 방법이 있습니까?

def test_skip(thing): 
    return thing == 'b' 

def num_to_skip(thing): 
    return 3 

def process_things(things): 
    """ 
    build list from things where we skip every test_skip() and the next num_to_skip() items 
    """ 
    result = [] 
    skip_count = 0 
    for thing in things: 
     if test_skip(thing): 
      skip_count = num_to_skip(thing) 
     if skip_count > 0: 
      skip_count -= 1 
      continue 
     result.append(thing) 
    return result 

source = list('abzzazyabyyab') 
intended_result = list('aazyaa') 

assert process_things(source) == intended_result 

답변

4

당신은 반복자와 itertools에서 consume 조리법을 사용할 수 있습니다. consume(iterator, n)을 호출하면 이 n 개 항목으로 늘어납니다. iterator에 대해 for-looping하는 동안 호출하면, 첫 번째 항목 consume이 소비되지 않았을 때 다음 반복이 시작됩니다.

import collections 
from itertools import islice 

def consume(iterator, n): 
    "Advance the iterator n-steps ahead. If n is none, consume entirely." 
    # Use functions that consume iterators at C speed. 
    if n is None: 
     # feed the entire iterator into a zero-length deque 
     collections.deque(iterator, maxlen=0) 
    else: 
     # advance to the empty slice starting at position n 
     next(islice(iterator, n, n), None) 

def process_things(things): 
    """ 
    build list from things where we skip every test_skip() and the next num_to_skip() items 
    """ 
    result = [] 
    things = iter(things) 
    for thing in things: 
     if test_skip(thing): 
      consume(things, num_to_skip(thing) - 1) 
     else: 
      result.append(thing) 
    return result 

test_skip은 건너 뛸 말한다 항목을 칠 때 나는, process_things를 작성한 방법, 그것은 생략 할 num_to_skip(thing) 항목에서 해당 항목을 계산합니다. 이는 코드가 수행하는 것과 일치하지만 "목록에서 다음 항목을 건너 뜁니다"는 설명과 정확히 일치하지 않습니다.

관련 문제