从Python迭代器获取最后一项的最简洁方法

时间:2022-07-27 18:19:31

What's the best way of getting the last item from an iterator in Python 2.6? For example, say

在Python 2.6中从迭代器获取最后一项的最佳方法是什么?例如,说

my_iter = iter(range(5))

What is the shortest-code / cleanest way of getting 4 from my_iter?

什么是从my_iter获得4的最短代码/最干净的方法?

I could do this, but it doesn't seem very efficient:

我可以做到这一点,但它看起来效率不高:

[x for x in my_iter][-1]

11 个解决方案

#1


69  

item = defaultvalue
for item in my_iter:
    pass

#2


40  

Use a deque of size 1.

使用大小为1的双端队列。

from collections import deque

#aa is an interator
aa = iter('apple')

dd = deque(aa, maxlen=1)
last_element = dd.pop()

#3


28  

Probably worth using __reversed__ if it is available

如果可用的话,可能值得使用__reversed__

if hasattr(my_iter,'__reversed__'):
    last = next(reversed(my_iter))
else:
    for last in my_iter:
        pass

#4


20  

If you are using python 3.x:

如果您使用的是python 3.x:

*_, last = iterator # for a better understanding check PEP 448
print(last)

if you are using python 2.7:

如果您使用的是python 2.7:

last = next(iterator)
for last in iterator:
    continue
print last

#5


18  

This is unlikely to be faster than the empty for loop due to the lambda, but maybe it will give someone else an idea

由于lambda,这不太可能比空循环更快,但也许它会给别人一个想法

reduce(lambda x,y:y,my_iter)

If the iter is empty, a TypeError is raised

如果iter为空,则引发TypeError

#6


16  

As simple as:

很简单:

max(enumerate(the_iter))[1]

#7


4  

There's this

就是这样

list( the_iter )[-1]

If the length of the iteration is truly epic -- so long that materializing the list will exhaust memory -- then you really need to rethink the design.

如果迭代的长度真的是史诗般的 - 只要实现列表就会耗尽内存 - 那么你真的需要重新考虑设计。

#8


2  

I would use reversed, except that it only takes sequences instead of iterators, which seems rather arbitrary.

我会使用反转,除了它只需要序列而不是迭代器,这看似相当随意。

Any way you do it, you'll have to run through the entire iterator. At maximum efficiency, if you don't need the iterator ever again, you could just trash all the values:

无论如何,你都必须遍历整个迭代器。以最高效率,如果您不再需要迭代器,您可以删除所有值:

for last in my_iter:
    pass
# last is now the last item

I think this is a sub-optimal solution, though.

不过,我认为这是次优解决方案。

#9


1  

See this code for something similar:

请参阅此代码以获取类似内容:

http://excamera.com/sphinx/article-islast.html

http://excamera.com/sphinx/article-islast.html

you might use it to pick up the last item with:

您可以使用它来获取最后一项:

[(last, e) for (last, e) in islast(the_iter) if last]

#10


0  

I would just use next(reversed(myiter))

我会用下一个(逆转(myiter))

#11


-7  

The question is wrong and can only lead to an answer that is complicated and inefficient. To get an iterator, you of course start out from something that is iterable, which will in most cases offer a more direct way of accessing the last element.

这个问题是错误的,只会导致一个复杂而低效的答案。要获得迭代器,您当然要从可迭代的东西开始,这在大多数情况下会提供更直接的方式来访问最后一个元素。

Once you create an iterator from an iterable you are stuck in going through the elements, because that is the only thing an iterable provides.

一旦从迭代中创建迭代器,就会遇到遍历元素的问题,因为这是迭代提供的唯一内容。

So, the most efficient and clear way is not to create the iterator in the first place but to use the native access methods of the iterable.

因此,最有效和最明确的方法不是首先创建迭代器,而是使用iterable的本机访问方法。

#1


69  

item = defaultvalue
for item in my_iter:
    pass

#2


40  

Use a deque of size 1.

使用大小为1的双端队列。

from collections import deque

#aa is an interator
aa = iter('apple')

dd = deque(aa, maxlen=1)
last_element = dd.pop()

#3


28  

Probably worth using __reversed__ if it is available

如果可用的话,可能值得使用__reversed__

if hasattr(my_iter,'__reversed__'):
    last = next(reversed(my_iter))
else:
    for last in my_iter:
        pass

#4


20  

If you are using python 3.x:

如果您使用的是python 3.x:

*_, last = iterator # for a better understanding check PEP 448
print(last)

if you are using python 2.7:

如果您使用的是python 2.7:

last = next(iterator)
for last in iterator:
    continue
print last

#5


18  

This is unlikely to be faster than the empty for loop due to the lambda, but maybe it will give someone else an idea

由于lambda,这不太可能比空循环更快,但也许它会给别人一个想法

reduce(lambda x,y:y,my_iter)

If the iter is empty, a TypeError is raised

如果iter为空,则引发TypeError

#6


16  

As simple as:

很简单:

max(enumerate(the_iter))[1]

#7


4  

There's this

就是这样

list( the_iter )[-1]

If the length of the iteration is truly epic -- so long that materializing the list will exhaust memory -- then you really need to rethink the design.

如果迭代的长度真的是史诗般的 - 只要实现列表就会耗尽内存 - 那么你真的需要重新考虑设计。

#8


2  

I would use reversed, except that it only takes sequences instead of iterators, which seems rather arbitrary.

我会使用反转,除了它只需要序列而不是迭代器,这看似相当随意。

Any way you do it, you'll have to run through the entire iterator. At maximum efficiency, if you don't need the iterator ever again, you could just trash all the values:

无论如何,你都必须遍历整个迭代器。以最高效率,如果您不再需要迭代器,您可以删除所有值:

for last in my_iter:
    pass
# last is now the last item

I think this is a sub-optimal solution, though.

不过,我认为这是次优解决方案。

#9


1  

See this code for something similar:

请参阅此代码以获取类似内容:

http://excamera.com/sphinx/article-islast.html

http://excamera.com/sphinx/article-islast.html

you might use it to pick up the last item with:

您可以使用它来获取最后一项:

[(last, e) for (last, e) in islast(the_iter) if last]

#10


0  

I would just use next(reversed(myiter))

我会用下一个(逆转(myiter))

#11


-7  

The question is wrong and can only lead to an answer that is complicated and inefficient. To get an iterator, you of course start out from something that is iterable, which will in most cases offer a more direct way of accessing the last element.

这个问题是错误的,只会导致一个复杂而低效的答案。要获得迭代器,您当然要从可迭代的东西开始,这在大多数情况下会提供更直接的方式来访问最后一个元素。

Once you create an iterator from an iterable you are stuck in going through the elements, because that is the only thing an iterable provides.

一旦从迭代中创建迭代器,就会遇到遍历元素的问题,因为这是迭代提供的唯一内容。

So, the most efficient and clear way is not to create the iterator in the first place but to use the native access methods of the iterable.

因此,最有效和最明确的方法不是首先创建迭代器,而是使用iterable的本机访问方法。