问题:如何在Python中获取列表的最后一项?

我需要列表的最后9个数字,而且我敢肯定有一种切片方法,但是我似乎无法理解。我可以这样获得前9个:

num_list[0:9]

I need the last 9 numbers of a list and I’m sure there is a way to do it with slicing, but I can’t seem to get it. I can get the first 9 like this:

num_list[0:9]

回答 0

您可以在切片运算符中使用负整数。这是使用python CLI解释器的示例:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a[-9:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]

重要的是 a[-9:]

You can use negative integers with the slicing operator for that. Here’s an example using the python CLI interpreter:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a[-9:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]

the important line is a[-9:]


回答 1

负索引将从列表的末尾开始计数,因此:

num_list[-9:]

a negative index will count from the end of the list, so:

num_list[-9:]

回答 2

切片

Python切片是一项非常快的操作,它是一种快速访问部分数据的便捷方法。

从列表(或支持字符串的任何其他序列,如字符串)中获取最后九个元素的切片表示法如下所示:

num_list[-9:]

看到此内容时,我将括号中的部分读为“从末尾到第9位”。(实际上,我在心理上将其缩写为“ -9,on”)

说明:

完整的符号是

sequence[start:stop:step]

但是冒号是告诉Python您给它一个切片而不是常规索引的原因。这就是为什么在Python 2中复制列表的惯用方式是

list_copy = sequence[:]

清除它们的方法是:

del my_list[:]

(清单get list.copylist.clearin Python3。)

给您的切片起一个描述性的名字!

您可能会发现,将形成切片与将切片传递给list.__getitem__方法分开很有用(这就是方括号所做的事情)。即使您并不陌生,它也可以使您的代码更具可读性,以便其他可能需要阅读您的代码的人可以更轻松地了解您的操作。

但是,您不能仅将一些用冒号分隔的整数分配给变量。您需要使用slice对象:

last_nine_slice = slice(-9, None)

第二个参数,None,是必需的,使得第一参数被解释为所述start参数否则这将是stop自变量

然后可以将slice对象传递给序列:

>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]

islice

islice从itertools模块中获取是另一种可能的有效方法。islice不会接受否定参数,因此理想情况下,您的iterable具有一个__reversed__特殊的方法-列表确实具有-因此您必须先将您的列表(或with的iterable __reversed__)传递给reversed

>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>

islice允许对数据管道进行延迟评估,因此要实现数据,请将其传递给构造函数(如list):

>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]

Slicing

Python slicing is an incredibly fast operation, and it’s a handy way to quickly access parts of your data.

Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:

num_list[-9:]

When I see this, I read the part in the brackets as “9th from the end, to the end.” (Actually, I abbreviate it mentally as “-9, on”)

Explanation:

The full notation is

sequence[start:stop:step]

But the colon is what tells Python you’re giving it a slice and not a regular index. That’s why the idiomatic way of copying lists in Python 2 is

list_copy = sequence[:]

And clearing them is with:

del my_list[:]

(Lists get list.copy and list.clear in Python 3.)

Give your slices a descriptive name!

You may find it useful to separate forming the slice from passing it to the list.__getitem__ method (that’s what the square brackets do). Even if you’re not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you’re doing.

However, you can’t just assign some integers separated by colons to a variable. You need to use the slice object:

last_nine_slice = slice(-9, None)

The second argument, None, is required, so that the first argument is interpreted as the start argument otherwise it would be the stop argument.

You can then pass the slice object to your sequence:

>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]

islice

islice from the itertools module is another possibly performant way to get this. islice doesn’t take negative arguments, so ideally your iterable has a __reversed__ special method – which list does have – so you must first pass your list (or iterable with __reversed__) to reversed.

>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>

islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list):

>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]

回答 3

您可以根据需要使用numlist [-9:]从左到右读取最后9个元素,或者使用numlist [:-10:-1]从右到左读取。

>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]

The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.

>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]

回答 4

这是获取迭代的“ tail”项的几个选项:

给定

n = 9
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

期望的输出

[2, 3, 4, 5, 6, 7, 8, 9, 10]

我们使用以下任一选项获取后者的输出:

from collections import deque
import itertools

import more_itertools


# A: Slicing
iterable[-n:]


# B: Implement an itertools recipe
def tail(n, iterable):
    """Return an iterator over the last *n* items of *iterable*.

        >>> t = tail(3, 'ABCDEFG')
        >>> list(t)
        ['E', 'F', 'G']

    """
    return iter(deque(iterable, maxlen=n))
list(tail(n, iterable))


# C: Use an implemented recipe, via more_itertools
list(more_itertools.tail(n, iterable))


# D: islice, via itertools
list(itertools.islice(iterable, len(iterable)-n, None))


# E: Negative islice, via more_itertools
list(more_itertools.islice_extended(iterable, -n, None))

细节

  • 答:传统的Python 切片是该语言固有的功能。此选项适用于序列,例如字符串,列表和元组。但是,这种切片不适用于迭代器,例如iter(iterable)
  • B. 。它可以普遍适用于任何可迭代的对象,并且可以解决最后一个解决方案中的迭代器问题。此配方必须手动实现,因为它尚未正式包含在itertools模块中。
  • C.许多配方,包括后一种工具(B),都已在第三方软件包中方便地实现。安装和导入这些库可以避免手动实施。这些库之一称为more_itertools(通过安装> pip install more-itertools);见more_itertools.tail
  • D. itertools图书馆的成员。注意,itertools.islice 不支持负片
  • E.实现了另一种工具,more_itertools该工具可以概括itertools.islice为支持负切片;见more_itertools.islice_extended

我要使用哪一个?

这要看情况。在大多数情况下,切片(如其他答案中所述的选项A)是语言中最简单的选项,并且支持大多数可迭代类型。对于更通用的迭代器,请使用其余任何选项。请注意,选项C和E需要安装第三方库,某些用户可能会觉得有用。

Here are several options for getting the “tail” items of an iterable:

Given

n = 9
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Desired Output

[2, 3, 4, 5, 6, 7, 8, 9, 10]

Code

We get the latter output using any of the following options:

from collections import deque
import itertools

import more_itertools


# A: Slicing
iterable[-n:]


# B: Implement an itertools recipe
def tail(n, iterable):
    """Return an iterator over the last *n* items of *iterable*.

        >>> t = tail(3, 'ABCDEFG')
        >>> list(t)
        ['E', 'F', 'G']

    """
    return iter(deque(iterable, maxlen=n))
list(tail(n, iterable))


# C: Use an implemented recipe, via more_itertools
list(more_itertools.tail(n, iterable))


# D: islice, via itertools
list(itertools.islice(iterable, len(iterable)-n, None))


# E: Negative islice, via more_itertools
list(more_itertools.islice_extended(iterable, -n, None))

Details

  • A. Traditional Python slicing is inherent to the language. This option works with sequences such as strings, lists and tuples. However, this kind of slicing does not work on iterators, e.g. iter(iterable).
  • B. An . It is generalized to work on any iterable and resolves the iterator issue in the last solution. This recipe must be implemented manually as it is not officially included in the itertools module.
  • C. Many recipes, including the latter tool (B), have been conveniently implemented in third party packages. Installing and importing these these libraries obviates manual implementation. One of these libraries is called more_itertools (install via > pip install more-itertools); see more_itertools.tail.
  • D. A member of the itertools library. Note, itertools.islice does not support negative slicing.
  • E. Another tool is implemented in more_itertools that generalizes itertools.islice to support negative slicing; see more_itertools.islice_extended.

Which one do I use?

It depends. In most cases, slicing (option A, as mentioned in other answers) is most simple option as it built into the language and supports most iterable types. For more general iterators, use any of the remaining options. Note, options C and E require installing a third-party library, which some users may find useful.


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