How to delete last item in list?

后端 未结 7 679
再見小時候
再見小時候 2021-01-30 06:08

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 calcula

相关标签:
7条回答
  • 2021-01-30 06:18

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

    0 讨论(0)
  • 2021-01-30 06:24

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

    • https://github.com/brouberol/timer-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
    
    0 讨论(0)
  • 2021-01-30 06:27

    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

    0 讨论(0)
  • 2021-01-30 06:30

    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
    
    0 讨论(0)
  • 2021-01-30 06:31

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

    0 讨论(0)
  • 2021-01-30 06:35

    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.

    0 讨论(0)
提交回复
热议问题