简体   繁体   English

Python 从生成器项中获取最后一个元素

[英]Python get the last element from generator items

I'm super amazed using the generator instead of list.我非常惊讶使用生成器而不是列表。 But I can't find any solution for this question.但我找不到这个问题的任何解决方案。

What is the efficient way to get the first and last element from generator items?从生成器项中获取第一个和最后一个元素的有效方法是什么? Because with list we can just do lst[0] and lst[-1]因为使用 list 我们可以只做 lst[0] 和 lst[-1]

Thanks for the help.谢谢您的帮助。 I can't provide any codes since it's clearly that's just what I want to know :)我无法提供任何代码,因为这显然正是我想知道的:)

You have to iterate through the whole thing.你必须遍历整个事情。 Say you have this generator:假设你有这个生成器:

def foo():
    yield 0
    yield 1
    yield 2
    yield 3

The easiest way to get the first and last value would be to convert the generator into a list.获取第一个和最后一个值的最简单方法是将生成器转换为列表。 Then access the values using list lookups.然后使用列表查找访问这些值。

data = list(foo())
print(data[0], data[-1])

If you want to avoid creating a container, you could use a for-loop to exhaust the generator.如果您想避免创建容器,您可以使用 for 循环来耗尽生成器。

gen = foo()
first = last = next(gen)
for last in gen: pass

print(first, last)

Note: You'll want to special case this when there are no values produced by the generator.注意:当生成器没有生成值时,您需要特殊情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM