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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18169965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:01:54  来源:igfitidea点击:

How to delete last item in list?

pythontimepython-3.x

提问by Samir

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.

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

采纳答案by sebastian

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)

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

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

注 2:代码可能会使用一些 Python 习语。我强烈推荐阅读这篇:
Code Like a Pythonista: Idiomatic Python(via wayback machine archive)。

回答by paxdiablo

You need:

你需要:

record = record[:-1]

before the forloop.

for循环之前。

This will set recordto the current recordlist but withoutthe last item. You may, depending on your needs, want to ensure the list isn't empty before doing this.

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

回答by miku

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

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

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 Timercontext manager in full:

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

回答by John La Rooy

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

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

回答by Maciej Gol

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

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

回答by FlyingZebra1

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

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

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

回答by Greko2015 GuFn

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

list.pop()如果您想以另一种方式使用,只需立即使用:list.popleft()