如何删除列表中的最后一项?

问题:如何删除列表中的最后一项?

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

I have this program that calculates the time taken to answer a specific question, and quits out of the while loop when answer is incorrect, but i want to delete the last calculation, so i can call min() and it not be the wrong time, sorry if this is confusing.

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))

回答 0

如果我正确理解了问题,则可以使用切片符号保留除最后一项以外的所有内容:

record = record[:-1]

但是更好的方法是直接删除该项目:

del record[-1]

注意1:请注意,使用record = record [:-1]并不会真正删除最后一个元素,而是将子列表分配给record。如果您在函数中运行它并且record是参数,则这会有所不同。使用record = record [:-1]时,原始列表(函数外部)保持不变,而使用del record [-1]或record.pop()时,列表将更改。(如@pltrdy在评论中所述)

注意2:代码可以使用一些Python惯用法。我强烈建议您阅读:
像Pythonista一样的代码:惯用的Python(通过Wayback机器档案)。

If I understood the question correctly, you can use the slicing notation to keep everything except the last item:

record = record[:-1]

But a better way is to delete the item directly:

del record[-1]

Note 1: Note that using record = record[:-1] does not really remove the last element, but assign the sublist to record. This makes a difference if you run it inside a function and record is a parameter. With record = record[:-1] the original list (outside the function) is unchanged, with del record[-1] or record.pop() the list is changed. (as stated by @pltrdy in the comments)

Note 2: The code could use some Python idioms. I highly recommend reading this:
Code Like a Pythonista: Idiomatic Python (via wayback machine archive).


回答 1

你应该用这个

del record[-1]

问题所在

record = record[:-1]

是因为它每次删除项目时都会复制列表,所以效率不是很高

you should use this

del record[-1]

The problem with

record = record[:-1]

Is that it makes a copy of the list every time you remove an item, so isn’t very efficient


回答 2

list.pop() 删除并返回列表的最后一个元素。

list.pop() removes and returns the last element of the list.


回答 3

你需要:

record = record[:-1]

for循环之前。

这将设置record为当前record列表,但没有最后一项。您可能会根据自己的需要,在执行此操作之前确保列表不为空。

You need:

record = record[:-1]

before the for loop.

This will set record to the current record list but without the last item. You may, depending on your needs, want to ensure the list isn’t empty before doing this.


回答 4

如果您在计时方面做得很多,我可以推荐这个小(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]

仅供参考,以下是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

If you do a lot with timing, I can recommend this little (20 line) context manager:

You code could look like this then:

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

回答 5

只是list.pop() 现在就使用,如果您愿意,可以使用另一种方法:list.popleft()

just simply use list.pop() now if you want it the other way use : list.popleft()


回答 6

如果您有一个列表列表(在我的情况下为tracked_output_sheet),要在其中删除每个列表的最后一个元素,则可以使用以下代码:

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

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