목록의 마지막 항목을 삭제하려면 어떻게 해야 합니까?
나는 특정 질문에 대답하는 데 걸리는 시간을 계산하고 답이 틀리면 while loop을 종료하는 이 프로그램을 가지고 있지만, 마지막 계산을 삭제하고 전화할 수 있도록 하고 싶다.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의 관용어가 몇 가지 사용될 수 있습니다.저는 이것을 읽는 것을 강력히 추천합니다.
Pythonista와 같은 코드: Idiomatic Python(웨이백 머신 아카이브 사용).
이것을 사용해야 한다.
del record[-1]
에 관한 문제
record = record[:-1]
아이템을 삭제할 때마다 리스트가 복사되기 때문에 효율적이지 않습니다.
list.pop()
는 목록의 마지막 요소를 삭제하고 반환합니다.
필요한 것은 다음과 같습니다.
record = record[:-1]
이 되기 전에for
고리.
이것은 설정됩니다.record
조류에 따라record
마지막 항목은 제외합니다.필요에 따라서는, 이 조작을 실시하기 전에, 리스트가 비어 있지 않은 것을 확인할 수 있습니다.
간단히 사용하다list.pop()
다른 방법으로 사용하고 싶은 경우는, 다음과 같이 합니다.list.popleft()
다음 예시와 같이 *list,_ = 목록을 사용해야 합니다.
record = [1,2,3]
*record,_ = record
record
---
[1, 2]
타이밍을 중시하는 경우는, 다음의 작은(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]
참고로 타이머 컨텍스트 매니저의 전체 내용은 다음과 같습니다.
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
각 목록에서 마지막 요소를 삭제하는 목록(이 경우 tracked_output_sheet)이 있는 경우 다음 코드를 사용할 수 있습니다.
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
'itsource' 카테고리의 다른 글
컨텍스트 경로 없이 요청 URI를 얻는 방법 (0) | 2022.09.14 |
---|---|
String Builder를 루프에서 재사용하는 것이 좋습니까? (0) | 2022.09.14 |
콘솔로 이동합니다.writline 및 System.out.println (0) | 2022.09.14 |
JavaScript에서 여러 CSS 스타일을 설정하려면 어떻게 해야 합니까? (0) | 2022.09.14 |
PHP가 $_GET 또는 $_POST 배열에서 '.' 문자의 치환을 중지하도록 합니다. (0) | 2022.09.14 |