Python 习惯用法返回第一项或 None

发布于 2024-07-10 10:11:50 字数 300 浏览 5 评论 0 原文

我正在调用一堆返回列表的方法。 该列表可能为空。 如果列表非空,我想返回第一项; 否则,我想返回None。 这段代码有效:

def main():
    my_list = get_list()
    if len(my_list) > 0:
        return my_list[0]
    return None

但在我看来,应该有一个简单的单行习惯用法来执行此操作。 有没有?

I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:

def main():
    my_list = get_list()
    if len(my_list) > 0:
        return my_list[0]
    return None

but it seems to me that there should be a simple one-line idiom for doing this. Is there?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

陌路终见情 2024-07-17 10:11:51
def head(iterable):
    try:
        return iter(iterable).next()
    except StopIteration:
        return None

print head(xrange(42, 1000)  # 42
print head([])               # None

顺便说一句:我会将您的一般程序流程重新设计为如下所示:(

lists = [
    ["first", "list"],
    ["second", "list"],
    ["third", "list"]
]

def do_something(element):
    if not element:
        return
    else:
        # do something
        pass

for li in lists:
    do_something(head(li))

尽可能避免重复)

def head(iterable):
    try:
        return iter(iterable).next()
    except StopIteration:
        return None

print head(xrange(42, 1000)  # 42
print head([])               # None

BTW: I'd rework your general program flow into something like this:

lists = [
    ["first", "list"],
    ["second", "list"],
    ["third", "list"]
]

def do_something(element):
    if not element:
        return
    else:
        # do something
        pass

for li in lists:
    do_something(head(li))

(Avoiding repetition whenever possible)

过气美图社 2024-07-17 10:11:51

借用 more_itertools.first_true 代码会产生不错的结果可读:

def first_true(iterable, default=None, pred=None):
    return next(filter(pred, iterable), default)

def get_first_non_default(items_list, default=None):
    return first_true(items_list, default, pred=lambda x: x!=default)

Borrowing more_itertools.first_true code yields something decently readable:

def first_true(iterable, default=None, pred=None):
    return next(filter(pred, iterable), default)

def get_first_non_default(items_list, default=None):
    return first_true(items_list, default, pred=lambda x: x!=default)
阳光下的泡沫是彩色的 2024-07-17 10:11:51

以下代码涵盖了使用 lambda 的几种场景:

l1 = [1,2,3]
l2 = []
l3 = None
first_elem = lambda x: x[0] if x else None
print(first_elem(l1))
print(first_elem(l2))
print(first_elem(l3))

Following code covers several scenarios by using lambda:

l1 = [1,2,3]
l2 = []
l3 = None
first_elem = lambda x: x[0] if x else None
print(first_elem(l1))
print(first_elem(l2))
print(first_elem(l3))
泪之魂 2024-07-17 10:11:51

如果您碰巧已经在使用 funcy 库....

...它为 python 提供了大量有用的、受函数式编程启发的实用程序——正如我经常发现自己所做的那样——然后,您可以利用...

first 函数来自他们关于序列相关函数的部分:

返回序列中的第一项。 如果序列为空,则返回 None。 典型用法是选择一些生成的变体中的第一个。

...然后你可以执行如下操作:

from funcy import first

my_list = get_list()
result = first(my_list) if my_list else None

If you happen to already be using the funcy library....

Image of Funcy's Docs

... which provides a large assortment of useful little functional-programming-inspired utilities for python--as I often find myself doing--then, you can take advantage of the...

first function from their section on Sequence-related functions:

Returns the first item in the sequence. Returns None if the sequence is empty. Typical usage is choosing first of some generated variants.

... Then you can do something like the following:

from funcy import first

my_list = get_list()
result = first(my_list) if my_list else None
萌酱 2024-07-17 10:11:51

使用 and-or 技巧:

a = get_list()
return a and a[0] or None

Using the and-or trick:

a = get_list()
return a and a[0] or None
橘寄 2024-07-17 10:11:51

可能不是最快的解决方案,但没有人提到这个选项:

dict(enumerate(get_list())).get(0)

如果 get_list() 可以返回 None 你可以使用:

dict(enumerate(get_list() or [])).get(0)

优点:

-one line

-you just call get_list () 一次

- 易于理解

Probably not the fastest solution, but nobody mentioned this option:

dict(enumerate(get_list())).get(0)

if get_list() can return None you can use:

dict(enumerate(get_list() or [])).get(0)

Advantages:

-one line

-you just call get_list() once

-easy to understand

彻夜缠绵 2024-07-17 10:11:51

我的用例只是设置局部变量的值。

就我个人而言,我发现 try and except 风格

items = [10, 20]
try: first_item = items[0]
except IndexError: first_item = None
print first_item

比切片列表更容易阅读。

items = [10, 20]
first_item = (items[:1] or [None, ])[0]
print first_item

My use case was only to set the value of a local variable.

Personally I found the try and except style cleaner to read

items = [10, 20]
try: first_item = items[0]
except IndexError: first_item = None
print first_item

than slicing a list.

items = [10, 20]
first_item = (items[:1] or [None, ])[0]
print first_item
最单纯的乌龟 2024-07-17 10:11:51

您可以使用提取方法。 换句话说,将该代码提取到您随后调用的方法中。

我不会尝试将其压缩得更多,单行似乎比冗长的版本更难阅读。 如果你使用提取方法,它就是一个衬垫;)

You could use Extract Method. In other words extract that code into a method which you'd then call.

I wouldn't try to compress it much more, the one liners seem harder to read than the verbose version. And if you use Extract Method, it's a one liner ;)

拥抱没勇气 2024-07-17 10:11:51

有几个人建议这样做:

list = get_list()
return list and list[0] or None

这在很多情况下都有效,但只有在 list[0] 不等于 0、False 或空字符串时才有效。 如果 list[0] 为 0、False 或空字符串,则该方法将错误地返回 None。

<块引用>

我在自己的代码中多次创建了此错误!

Several people have suggested doing something like this:

list = get_list()
return list and list[0] or None

That works in many cases, but it will only work if list[0] is not equal to 0, False, or an empty string. If list[0] is 0, False, or an empty string, the method will incorrectly return None.

I've created this bug in my own code one too many times !

も星光 2024-07-17 10:11:51

惯用的 python 不等于 C 风格的三元运算符

cond and true_expr or false_expr

吗?

list = get_list()
return list and list[0] or None

isn't the idiomatic python equivalent to C-style ternary operators

cond and true_expr or false_expr

ie.

list = get_list()
return list and list[0] or None
吻泪 2024-07-17 10:11:51
if mylist != []:

       print(mylist[0])

   else:

       print(None)
if mylist != []:

       print(mylist[0])

   else:

       print(None)
任性一次 2024-07-17 10:11:50

Python 2.6+

next(iter(your_list), None)

如果 your_list 可以是 None

next(iter(your_list or []), None)

Python 2.4

def get_first(iterable, default=None):
    if iterable:
        for item in iterable:
            return item
    return default

示例:

x = get_first(get_first_list())
if x:
    ...
y = get_first(get_second_list())
if y:
    ...

另一个选项是内联上述函数:

for x in get_first_list() or []:
    # process x
    break # process at most one item
for y in get_second_list() or []:
    # process y
    break

为了避免 break,您可以编写:

for x in yield_first(get_first_list()):
    x # process x
for y in yield_first(get_second_list()):
    y # process y

在哪里:

def yield_first(iterable):
    for item in iterable or []:
        yield item
        return

Python 2.6+

next(iter(your_list), None)

If your_list can be None:

next(iter(your_list or []), None)

Python 2.4

def get_first(iterable, default=None):
    if iterable:
        for item in iterable:
            return item
    return default

Example:

x = get_first(get_first_list())
if x:
    ...
y = get_first(get_second_list())
if y:
    ...

Another option is to inline the above function:

for x in get_first_list() or []:
    # process x
    break # process at most one item
for y in get_second_list() or []:
    # process y
    break

To avoid break you could write:

for x in yield_first(get_first_list()):
    x # process x
for y in yield_first(get_second_list()):
    y # process y

Where:

def yield_first(iterable):
    for item in iterable or []:
        yield item
        return
楠木可依 2024-07-17 10:11:50

最好的方法是这样的:

a = get_list()
return a[0] if a else None

您也可以在一行中完成,但对于程序员来说更难阅读:

return (get_list()[:1] or [None])[0]

The best way is this:

a = get_list()
return a[0] if a else None

You could also do it in one line, but it's much harder for the programmer to read:

return (get_list()[:1] or [None])[0]
予囚 2024-07-17 10:11:50
(get_list() or [None])[0]

那应该有效。


顺便说一句,我没有使用变量 list,因为它会覆盖内置的 list() 函数。

(get_list() or [None])[0]

That should work.


BTW I didn't use the variable list, because that overwrites the builtin list() function.

眼波传意 2024-07-17 10:11:50

最惯用的 Python 方法是在迭代器上使用 next(),因为列表是可迭代的。 就像 @JFSebastian 在 2011 年 12 月 13 日的评论中所说的那样。

next(iter(the_list), None) 如果 the_list 为空,则返回 None。 请参阅 next() Python 2.6+

或者如果您确定the_list 不为空:

iter(the_list).next() 请参阅迭代器.next() Python 2.2+

The most python idiomatic way is to use the next() on a iterator since list is iterable. just like what @J.F.Sebastian put in the comment on Dec 13, 2011.

next(iter(the_list), None) This returns None if the_list is empty. see next() Python 2.6+

or if you know for sure the_list is not empty:

iter(the_list).next() see iterator.next() Python 2.2+

岁月染过的梦 2024-07-17 10:11:50

Python 习惯用法返回第一项还是 None?

最Pythonic的方法是最受支持的答案所证明的,这是我读到这个问题时首先想到的。 下面是如何使用它,首先如果可能为空的列表被传递到函数中:

def get_first(l): 
    return l[0] if l else None

如果列表是从 get_list 函数返回的:

l = get_list()
return l[0] if l else None

Python 3.8 中的新功能,赋值表达式

赋值表达式使用就地赋值运算符(非正式地称为海象运算符),:=,Python 3.8 中的新功能,允许我们就地进行检查和赋值,从而实现单行:

return l[0] if (l := get_list()) else None

作为一名长期 Python 用户,这感觉就像我们试图在一行上做太多事情 - 我觉得这样做会是更好的风格,假定性能相同:

if l := get_list():
    return l[0]
return None

支持这一表述的是 Tim Peter 的 文章在 PEP 中提议对语言进行此项更改。 他没有提及第一个表述,但基于他确实喜欢的其他表述,我认为他不会介意。

此处演示了执行此操作的其他方法,并带有解释

for

当我开始尝试考虑巧妙的方法来执行此操作时,这是我想到的第二件事:

for item in get_list():
    return item

这假定函数在此结束,隐式返回 <如果 get_list 返回空列表,则 code>None 。 下面的显式代码完全等效:

for item in get_list():
    return item
return None

if some_list

还提出了以下内容(我更正了不正确的变量名称),它也使用隐式 None。 这比上面的更好,因为它使用逻辑检查而不是可能不会发生的迭代。 这应该更容易立即理解正在发生的事情。 但如果我们为了可读性和可维护性而编写,我们还应该在末尾添加显式的 return None

some_list = get_list()
if some_list:
    return some_list[0]

切片 or [None] 并选择第零个索引

这也是在最高票数的答案中:

return (get_list()[:1] or [None])[0]

该切片是不必要的,并且会在内存中创建一个额外的单项列表。 以下应该更具性能。 解释一下,如果布尔上下文中第一个元素为 False,则 or 返回第二个元素,因此如果 get_list 返回空列表,则表达式包含括号中的将返回一个包含“None”的列表,然后将通过 0 索引访问该列表:

return (get_list() or [None])[0]

下一个使用以下事实:如果第一个为 True<,则返回第二个项目/code> 在布尔上下文中,并且由于它引用了 my_list 两次,因此它并不比三元表达式更好(并且技术上不是单行表达式):

my_list = get_list() 
return (my_list and my_list[0]) or None

next

然后我们可以巧妙地使用以下内置 nextiter

return next(iter(get_list()), None)

解释一下,iter 返回一个带有 .next 方法的迭代器。 (Python 3 中的 .__next__。)然后内置的 next 调用该 .next 方法,如果迭代器耗尽,则返回我们默认的值。给,

冗余三元表达式(a if b else c)并循环下面

提出了以下建议,但相反的方式更好,因为逻辑通常在正数而不是负数中更好地被理解。 由于 get_list 被调用两次,除非以某种方式记住结果,否则它的性能会很差:

return None if not get_list() else get_list()[0]

更好的逆:

return get_list()[0] if get_list() else None

更好的是,使用局部变量,以便 get_list 仅调用一次,您就会首先讨论推荐的 Pythonic 解决方案:

l = get_list()
return l[0] if l else None

Python idiom to return first item or None?

The most Pythonic approach is what the most upvoted answer demonstrated, and it was the first thing to come to my mind when I read the question. Here's how to use it, first if the possibly empty list is passed into a function:

def get_first(l): 
    return l[0] if l else None

And if the list is returned from a get_list function:

l = get_list()
return l[0] if l else None

New in Python 3.8, Assignment Expressions

Assignment expressions use the in-place assignment operator (informally called the walrus operator), :=, new in Python 3.8, allows us to do the check and assignment in-place, allowing the one-liner:

return l[0] if (l := get_list()) else None

As a long-time Python user, this feels like we're trying to do too much on one line - I feel it would be better style to do the presumptively equally performant:

if l := get_list():
    return l[0]
return None

In support of this formulation is Tim Peter's essay in the PEP proposing this change to the language. He didn't address the first formulation, but based on the other formulations he did like, I don't think he would mind.

Other ways demonstrated to do this here, with explanations

for

When I began trying to think of clever ways to do this, this is the second thing I thought of:

for item in get_list():
    return item

This presumes the function ends here, implicitly returning None if get_list returns an empty list. The below explicit code is exactly equivalent:

for item in get_list():
    return item
return None

if some_list

The following was also proposed (I corrected the incorrect variable name) which also uses the implicit None. This would be preferable to the above, as it uses the logical check instead of an iteration that may not happen. This should be easier to understand immediately what is happening. But if we're writing for readability and maintainability, we should also add the explicit return None at the end:

some_list = get_list()
if some_list:
    return some_list[0]

slice or [None] and select zeroth index

This one is also in the most up-voted answer:

return (get_list()[:1] or [None])[0]

The slice is unnecessary, and creates an extra one-item list in memory. The following should be more performant. To explain, or returns the second element if the first is False in a boolean context, so if get_list returns an empty list, the expression contained in the parentheses will return a list with 'None', which will then be accessed by the 0 index:

return (get_list() or [None])[0]

The next one uses the fact that and returns the second item if the first is True in a boolean context, and since it references my_list twice, it is no better than the ternary expression (and technically not a one-liner):

my_list = get_list() 
return (my_list and my_list[0]) or None

next

Then we have the following clever use of the builtin next and iter

return next(iter(get_list()), None)

To explain, iter returns an iterator with a .next method. (.__next__ in Python 3.) Then the builtin next calls that .next method, and if the iterator is exhausted, returns the default we give, None.

redundant ternary expression (a if b else c) and circling back

The below was proposed, but the inverse would be preferable, as logic is usually better understood in the positive instead of the negative. Since get_list is called twice, unless the result is memoized in some way, this would perform poorly:

return None if not get_list() else get_list()[0]

The better inverse:

return get_list()[0] if get_list() else None

Even better, use a local variable so that get_list is only called one time, and you have the recommended Pythonic solution first discussed:

l = get_list()
return l[0] if l else None
著墨染雨君画夕 2024-07-17 10:11:50

如果您发现自己试图从列表理解中提取第一件事(或无),您可以切换到生成器来执行此操作,如下所示:

next((x for x in blah if cond), None)

优点:如果 blah 不可索引,则可以使用缺点:这是不熟悉的语法。 不过,它在修改和过滤 ipython 中的内容时很有用。

If you find yourself trying to pluck the first thing (or None) from a list comprehension you can switch to a generator to do it like:

next((x for x in blah if cond), None)

Pro: works if blah isn't indexable Con: it's unfamiliar syntax. It's useful while hacking around and filtering stuff in ipython though.

美人如玉 2024-07-17 10:11:50

OP 的解决方案已经接近完成,只需做一些事情就可以使其更加Pythonic。

其一,无需获取列表的长度。 Python 中的空列表在 if 检查中计算结果为 False。 只是简单地说

if list:

此外,分配给与保留字重叠的变量是一个非常糟糕的主意。 “list”是Python中的保留字。

因此,让我们将其更改为

some_list = get_list()
if some_list:

这里的许多解决方案都忽略的一个非常重要的一点是,所有 Python 函数/方法默认情况下都返回 None。 请尝试以下操作。

def does_nothing():
    pass

foo = does_nothing()
print foo

除非您需要返回 None 来提前终止函数,否则没有必要显式返回 None。 非常简洁,只需返回第一个条目(如果存在)。

some_list = get_list()
if some_list:
    return list[0]

最后,也许这是隐含的,但只是为了明确(因为 显式优于隐式),你不应该让你的函数从另一个函数获取列表; 只需将其作为参数传递即可。 所以,最终的结果将是

def get_first_item(some_list): 
    if some_list:
        return list[0]

my_list = get_list()
first_item = get_first_item(my_list)

正如我所说,OP 已经接近完成,只需进行一些修改即可使其具有您正在寻找的 Python 风格。

The OP's solution is nearly there, there are just a few things to make it more Pythonic.

For one, there's no need to get the length of the list. Empty lists in Python evaluate to False in an if check. Just simply say

if list:

Additionally, it's a very Bad Idea to assign to variables that overlap with reserved words. "list" is a reserved word in Python.

So let's change that to

some_list = get_list()
if some_list:

A really important point that a lot of solutions here miss is that all Python functions/methods return None by default. Try the following below.

def does_nothing():
    pass

foo = does_nothing()
print foo

Unless you need to return None to terminate a function early, it's unnecessary to explicitly return None. Quite succinctly, just return the first entry, should it exist.

some_list = get_list()
if some_list:
    return list[0]

And finally, perhaps this was implied, but just to be explicit (because explicit is better than implicit), you should not have your function get the list from another function; just pass it in as a parameter. So, the final result would be

def get_first_item(some_list): 
    if some_list:
        return list[0]

my_list = get_list()
first_item = get_first_item(my_list)

As I said, the OP was nearly there, and just a few touches give it the Python flavor you're looking for.

谈下烟灰 2024-07-17 10:11:50

关于习语,有一个名为 nth 的 itertools Recipe

来自 itertools 食谱:

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

如果您想要单行,请考虑安装一个为您实现此食谱的库,例如 more_itertools

import more_itertools as mit

mit.nth([3, 2, 1], 0)
# 3

mit.nth([], 0)                                             # default is `None`
# None

另一个工具仅返回第一项,名为 more_itertools.first

mit.first([3, 2, 1])
# 3

mit.first([], default=None)
# None

这些 itertool 一般适用于任何可迭代对象,而不仅仅是列表。

Regarding idioms, there is an itertools recipe called nth.

From itertools recipes:

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

If you want one-liners, consider installing a library that implements this recipe for you, e.g. more_itertools:

import more_itertools as mit

mit.nth([3, 2, 1], 0)
# 3

mit.nth([], 0)                                             # default is `None`
# None

Another tool is available that only returns the first item, called more_itertools.first.

mit.first([3, 2, 1])
# 3

mit.first([], default=None)
# None

These itertools scale generically for any iterable, not only for lists.

愛上了 2024-07-17 10:11:50
for item in get_list():
    return item
for item in get_list():
    return item
若有似无的小暗淡 2024-07-17 10:11:50

坦率地说,我不认为有更好的成语:你的表达清晰简洁——不需要任何“更好”的东西。 也许吧,但这确实是一个品味问题,您可以更改 if len(list) > 0:if list: - 空列表将始终评估为 False。

与此相关的是,Python不是Perl(没有双关语!),您不必获得尽可能酷的代码。
事实上,我在 Python 中见过的最糟糕的代码也非常酷:-)并且完全无法维护。

顺便说一句,我在这里看到的大多数解决方案都没有考虑 list[0] 计算结果为 False 时(例如空字符串或零) - 在这种情况下,它们都返回 None 而不是正确的元素。

Frankly speaking, I do not think there is a better idiom: your is clear and terse - no need for anything "better". Maybe, but this is really a matter of taste, you could change if len(list) > 0: with if list: - an empty list will always evaluate to False.

On a related note, Python is not Perl (no pun intended!), you do not have to get the coolest code possible.
Actually, the worst code I have seen in Python, was also very cool :-) and completely unmaintainable.

By the way, most of the solution I have seen here do not take into consideration when list[0] evaluates to False (e.g. empty string, or zero) - in this case, they all return None and not the correct element.

呆橘 2024-07-17 10:11:50

my_list[0] if len(my_list) else None

my_list[0] if len(my_list) else None

梦回梦里 2024-07-17 10:11:50

不确定这有多Pythonic,但在库中出现第一个函数之前,我将其包含在源代码中:

first = lambda l, default=None: next(iter(l or []), default)

它只是一行(符合黑色)并避免依赖关系。

Not sure how pythonic this is but until there is a first function in the library I include this in the source:

first = lambda l, default=None: next(iter(l or []), default)

It's just one line (conforms to black) and avoids dependencies.

花落人断肠 2024-07-17 10:11:50

出于好奇,我对其中两个解决方案进行了计时。 使用 return 语句提前结束 for 循环的解决方案在我的 Python 2.5.1 机器上稍微昂贵一些,我怀疑这与设置可迭代有关。

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

这些是我得到的时间:

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.

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.
吹梦到西洲 2024-07-17 10:11:50
try:
    return a[0]
except IndexError:
    return None
try:
    return a[0]
except IndexError:
    return None
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文