我有这个程序,计算回答特定问题所花费的时间,并在答案不正确时退出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))

当前回答

必须使用*list,_ = list,如下例所示

record = [1,2,3]
*record,_ = record
record
---
[1, 2]

其他回答

只需简单地使用list.pop() 现在,如果你想以另一种方式使用:list.popleft()

如果你有一个列表列表(在我的例子中是tracked_output_sheet),你想从每个列表中删除最后一个元素,你可以使用以下代码:

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

必须使用*list,_ = list,如下例所示

record = [1,2,3]
*record,_ = record
record
---
[1, 2]

如果你做了很多时间,我可以推荐这个小(20行)上下文管理器:

https://github.com/brouberol/timer-context-manager

你的代码可以是这样的:

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

你需要:

record = record[:-1]

在for循环之前。

这将把记录设置为当前记录列表,但不包含最后一项。根据需要,您可能希望在执行此操作之前确保列表不为空。