问题:如何获取python列表的第n个元素或默认值(如果不可用)

我在寻找dictionary.get(key, default)for清单的python中的等效项。是否有一个线性惯用法来获取列表的第n个元素或默认值(如果不可用)?

例如,给定一个列表myList我想要得到myList[0],如果myList为空列表则为5 。

谢谢。

I’m looking for an equivalent in python of dictionary.get(key, default) for lists. Is there any one liner idiom to get the nth element of a list or a default value if not available?

For example, given a list myList I would like to get myList[0], or 5 ifmyList is an empty list.

Thanks.


回答 0

l[index] if index < len(l) else default

为了支持负索引,我们可以使用:

l[index] if -len(l) <= index < len(l) else default
l[index] if index < len(l) else default

To support negative indices we can use:

l[index] if -len(l) <= index < len(l) else default

回答 1

try:
   a = b[n]
except IndexError:
   a = default

编辑:我删除了对TypeError的检查-可能最好让调用者处理。

try:
   a = b[n]
except IndexError:
   a = default

Edit: I removed the check for TypeError – probably better to let the caller handle this.


回答 2

(a[n:]+[default])[0]

a越大越好

(a[n:n+1]+[default])[0]

这是可行的,因为if a[n:]是一个空列表,ifn => len(a)

这是一个如何与 range(5)

>>> range(5)[3:4]
[3]
>>> range(5)[4:5]
[4]
>>> range(5)[5:6]
[]
>>> range(5)[6:7]
[]

和完整的表达

>>> (range(5)[3:4]+[999])[0]
3
>>> (range(5)[4:5]+[999])[0]
4
>>> (range(5)[5:6]+[999])[0]
999
>>> (range(5)[6:7]+[999])[0]
999
(a[n:]+[default])[0]

This is probably better as a gets larger

(a[n:n+1]+[default])[0]

This works because if a[n:] is an empty list if n => len(a)

Here is an example of how this works with range(5)

>>> range(5)[3:4]
[3]
>>> range(5)[4:5]
[4]
>>> range(5)[5:6]
[]
>>> range(5)[6:7]
[]

And the full expression

>>> (range(5)[3:4]+[999])[0]
3
>>> (range(5)[4:5]+[999])[0]
4
>>> (range(5)[5:6]+[999])[0]
999
>>> (range(5)[6:7]+[999])[0]
999

回答 3

刚刚发现:

next(iter(myList), 5)

iter(l)在上返回迭代器myListnext()消耗迭代器的第一个元素,并引发StopIteration错误,除非使用默认值调用(在这种情况下为第二个参数,5

这仅在您需要第一个元素时才有效,在您的示例中就是这种情况,但在您要提问的文本中不是如此,所以…

此外,它不需要在内存中创建临时列表,并且即使没有名称,它也可以用于任何可迭代的类型(请参阅Xiong Chiamiov对gruszczy答案的评论)

Just discovered that :

next(iter(myList), 5)

iter(l) returns an iterator on myList, next() consumes the first element of the iterator, and raises a StopIteration error except if called with a default value, which is the case here, the second argument, 5

This only works when you want the 1st element, which is the case in your example, but not in the text of you question, so…

Additionally, it does not need to create temporary lists in memory and it works for any kind of iterable, even if it does not have a name (see Xiong Chiamiov’s comment on gruszczy’s answer)


回答 4

(L[n:n+1] or [somedefault])[0]
(L[n:n+1] or [somedefault])[0]

回答 5

…在dict.get(key, default)for列表中寻找python中的等效项

有一个itertools配方可用于常规可迭代对象。为了方便起见,您可以> pip install more_itertools导入此为您实现此类配方的第三方库:

import more_itertools as mit


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

mit.nth([], 0, 5)
# 5    

详情

这是nth配方的实现:

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

像一样dict.get(),此工具返回缺失索引的默认值。它适用于一般可迭代项:

mit.nth((0, 1, 2), 1)                                      # tuple
# 1

mit.nth(range(3), 1)                                       # range generator (py3)
# 1

mit.nth(iter([0, 1, 2]), 1)                                # list iterator 
# 1  

… looking for an equivalent in python of dict.get(key, default) for lists

There is an itertools recipes that does this for general iterables. For convenience, you can > pip install more_itertools and import this third-party library that implements such recipes for you:

Code

import more_itertools as mit


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

mit.nth([], 0, 5)
# 5    

Detail

Here is the implementation of the nth recipe:

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

Like dict.get(), this tool returns a default for missing indices. It applies to general iterables:

mit.nth((0, 1, 2), 1)                                      # tuple
# 1

mit.nth(range(3), 1)                                       # range generator (py3)
# 1

mit.nth(iter([0, 1, 2]), 1)                                # list iterator 
# 1  

回答 6

一种便宜的解决方案是.get()像往常一样使用枚举和用法来真正做出命令。

 dict(enumerate(l)).get(7, my_default)

A cheap solution is to really make a dict with enumerate and use .get() as usual, like

 dict(enumerate(l)).get(7, my_default)

回答 7

将@Joachim与上述内容结合使用,您可以使用

next(iter(my_list[index:]), default)

例子:

next(iter(range(10)[8:]), 11)
8
>>> next(iter(range(10)[12:]), 11)
11

或者,也许更清楚,但是没有 len

my_list[index] if my_list[index:] else default

Combining @Joachim’s with the above, you could use

next(iter(my_list[index:]), default)

Examples:

next(iter(range(10)[8:]), 11)
8
>>> next(iter(range(10)[12:]), 11)
11

Or, maybe more clear, but without the len

my_list[index] if my_list[index:] else default

回答 8

使用Python 3.4 contextlib.suppress(exceptions)构建getitem()类似于的方法getattr()

import contextlib

def getitem(iterable, index, default=None):
    """Return iterable[index] or default if IndexError is raised."""
    with contextlib.suppress(IndexError):
        return iterable[index]
    return default

Using Python 3.4’s contextlib.suppress(exceptions) to build a getitem() method similar to getattr().

import contextlib

def getitem(iterable, index, default=None):
    """Return iterable[index] or default if IndexError is raised."""
    with contextlib.suppress(IndexError):
        return iterable[index]
    return default

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。