Python idiom to return first item or None

后端 未结 24 1970
清酒与你
清酒与你 2020-12-07 07:46

I\'m sure there\'s a simpler way of doing this that\'s just not occurring to me.

I\'m calling a bunch of methods that return a list. The list may be empty. If the

24条回答
  •  萌比男神i
    2020-12-07 08:06

    Out of curiosity, I ran timings on two of the solutions. The solution which uses a return statement to prematurely end a for loop is slightly more costly on my machine with Python 2.5.1, I suspect this has to do with setting up the iterable.

    import random
    import timeit
    
    def index_first_item(some_list):
        if some_list:
            return some_list[0]
    
    
    def return_first_item(some_list):
        for item in some_list:
            return item
    
    
    empty_lists = []
    for i in range(10000):
        empty_lists.append([])
    
    assert empty_lists[0] is not empty_lists[1]
    
    full_lists = []
    for i in range(10000):
        full_lists.append(list([random.random() for i in range(10)]))
    
    mixed_lists = empty_lists[:50000] + full_lists[:50000]
    random.shuffle(mixed_lists)
    
    if __name__ == '__main__':
        ENV = 'import firstitem'
        test_data = ('empty_lists', 'full_lists', 'mixed_lists')
        funcs = ('index_first_item', 'return_first_item')
        for data in test_data:
            print "%s:" % data
            for func in funcs:
                t = timeit.Timer('firstitem.%s(firstitem.%s)' % (
                    func, data), ENV)
                times = t.repeat()
                avg_time = sum(times) / len(times)
                print "  %s:" % func
                for time in times:
                    print "    %f seconds" % time
                print "    %f seconds avg." % avg_time
    

    These are the timings I got:

    empty_lists:
      index_first_item:
        0.748353 seconds
        0.741086 seconds
        0.741191 seconds
        0.743543 seconds avg.
      return_first_item:
        0.785511 seconds
        0.822178 seconds
        0.782846 seconds
        0.796845 seconds avg.
    full_lists:
      index_first_item:
        0.762618 seconds
        0.788040 seconds
        0.786849 seconds
        0.779169 seconds avg.
      return_first_item:
        0.802735 seconds
        0.878706 seconds
        0.808781 seconds
        0.830074 seconds avg.
    mixed_lists:
      index_first_item:
        0.791129 seconds
        0.743526 seconds
        0.744441 seconds
        0.759699 seconds avg.
      return_first_item:
        0.784801 seconds
        0.785146 seconds
        0.840193 seconds
        0.803380 seconds avg.
    

提交回复
热议问题