IT story

목록에서 마지막 항목을 삭제하는 방법은 무엇입니까?

hot-time 2020. 8. 10. 08:08
반응형

목록에서 마지막 항목을 삭제하는 방법은 무엇입니까?


특정 질문에 답하는 데 걸리는 시간을 계산하고 답이 틀렸을 때 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))

질문을 올바르게 이해했다면 슬라이싱 표기법을 사용하여 마지막 항목을 제외한 모든 항목을 유지할 수 있습니다.

record = record[:-1]

그러나 더 좋은 방법은 항목을 직접 삭제하는 것입니다.

del record[-1]

참고 1 : record = record [:-1]을 사용하면 실제로 마지막 요소가 제거되지는 않지만 레코드에 하위 목록을 할당합니다. 함수 내에서 실행하고 레코드가 매개 변수 인 경우 차이가 있습니다. record = record [:-1]을 사용하면 원래 목록 (함수 외부)은 변경되지 않고 del record [-1] 또는 record.pop ()을 사용하면 목록이 변경됩니다. (댓글에서 @pltrdy가 언급했듯이)

참고 2 : 코드는 일부 Python 관용구를 사용할 수 있습니다. 나는 이것을 읽을 것을 강력히 추천한다 :
Code Like a Pythonista : Idiomatic Python (via wayback machine archive).


당신은 이것을 사용해야합니다

del record[-1]

문제

record = record[:-1]

항목을 제거 할 때마다 목록의 복사본을 만드는 것이므로 매우 효율적이지 않습니다.


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


다음이 필요합니다.

record = record[:-1]

for루프 전에 .

이 설정합니다 record현재에 record목록 만 하지 않고 마지막 항목. 필요에 따라이 작업을 수행하기 전에 목록이 비어 있지 않은지 확인할 수 있습니다.


타이밍을 많이 사용한다면이 작은 (20 줄) 컨텍스트 관리자를 추천 할 수 있습니다.

코드는 다음과 같이 보일 수 있습니다.

#!/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]

Just for reference, here's the content of the Timer context manager in full:

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

If you have a list of lists (tracked_output_sheet in my case), where you want to delete last element from each list, you can use the following code:

interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim

참고URL : https://stackoverflow.com/questions/18169965/how-to-delete-last-item-in-list

반응형