2013-08-11 2 views
23

나는 특정 질문에 대답하는 데 걸리는 시간을 계산하고 대답이 틀렸을 때 while 루프에서 빠져 나오지만 마지막 계산을 삭제하려고하는데이 프로그램은 min()으로 전화를 걸 수 있으며 잘못된 시간이 아닐 수 있습니다 죄송합니다. 혼란스러운 경우.파이썬 | 목록의 마지막 항목을 삭제하는 방법?

from time import time 

q = input('What do you want to type? ') 
a = ' ' 
record = [] 
while a != '': 
    start = time() 
    a = input('Type: ') 
    end = time() 
    v = end-start 
    record.append(v) 
    if a == q: 
     print('Time taken to type name: {:.2f}'.format(v)) 
    else: 
     break 
for i in record: 
    print('{:.2f} seconds.'.format(i)) 

답변

38

, 당신은 마지막 항목을 제외하고 모든 것을 유지하기 위해 슬라이스 표기법을 사용할 수 있습니다 파이썬 관용구.

당신의 코드처럼 볼 수 있었다 : 당신이 타이밍을 많이 할 경우에, 나는이 작은 (20 라인) 컨텍스트 관리자를 추천 할 수 http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

+1

굉장한 링크, 뒷주머니에 보관하겠습니다. – SethMMorton

3

당신이해야 할 다음 for 루프 전에

record = record[:-1] 

.

이것은 record을 현재 record 목록으로 설정하고 없이 마지막 항목으로 설정합니다. 필요에 따라 목록을 비우기 전에이를 확인하십시오.

코드 일부를 사용할 수 있습니다 : -

기록 = 기록 [: 1] 내가 질문을 제대로 이해하면

+0

나는 보았다, 고마워! – Samir

+2

'record.pop()'도 사용할 수 있습니까? (NB : 나는 파이썬에 대해 아주 익숙하다.) – CodeBeard

+1

예, record.pop()을 사용할 수도 있습니다. http://docs.python.org/3.3/tutorial/datastructures.html을 참조하십시오. – Bastiano9

2

: 내가보기 엔이 읽어 보시기 바랍니다 다음이 :

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

from timer import Timer 

if __name__ == '__main__': 
    a, record = None, [] 
    while not a == '': 
     with Timer() as t: # everything in the block will be timed 
      a = input('Type: ') 
     record.append(t.elapsed_s) 
    # drop the last item (makes a copy of the list): 
    record = record[:-1] 
    # or just delete it: 
    # del record[-1] 

그냥 참조를 위해, 여기에 전체의 Timer 컨텍스트 관리자의 내용이다 :

from timeit import default_timer 

class Timer(object): 
    """ A timer as a context manager. """ 

    def __init__(self): 
     self.timer = default_timer 
     # measures wall clock time, not CPU time! 
     # On Unix systems, it corresponds to time.time 
     # On Windows systems, it corresponds to time.clock 

    def __enter__(self): 
     self.start = self.timer() # measure start time 
     return self 

    def __exit__(self, exc_type, exc_value, exc_traceback): 
     self.end = self.timer() # measure end time 
     self.elapsed_s = self.end - self.start # elapsed time, in seconds 
     self.elapsed_ms = self.elapsed_s * 1000 # elapsed time, in milliseconds 
+0

사실 이것은 처음 작성한 '시간'프로그램이지만, 모듈에 대해 좀 더 익숙해지면 살펴볼 것입니다. 감사합니다! – Samir

55

당신이

record = record[:-1] 

으로이

del record[-1] 

문제를 사용해야합니다 그것이 만드는인가요 항목을 제거 할 때마다 목록이 복사되므로 효율성이 떨어집니다.

+1

이것은 받아 들인 대답보다 나은 해결책입니다. –

18

list.pop()은 목록의 마지막 요소를 제거하고 반환합니다.

관련 문제