如何删除列表中的最后一项? [英] How to delete last item in list?

查看:41
本文介绍了如何删除列表中的最后一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个程序可以计算回答特定问题所需的时间,并在答案不正确时退出 while 循环,但我想删除最后一个计算,所以我可以调用 min() 并且现在不是错误的时间,对不起,如果这令人困惑.

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

推荐答案

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

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]

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

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)

注 2:代码可能会使用一些 Python 习语.我强烈建议阅读此内容:
类似代码一个 Pythonista:惯用的 Python(通过回溯机器存档).

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

这篇关于如何删除列表中的最后一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆