code

Python 반복기에서 마지막 항목을 가져 오는 가장 깨끗한 방법

codestyles 2020. 8. 21. 07:45
반응형

Python 반복기에서 마지막 항목을 가져 오는 가장 깨끗한 방법


Python 2.6의 반복기에서 마지막 항목을 가져 오는 가장 좋은 방법은 무엇입니까? 예를 들어

my_iter = iter(range(5))

지고의 짧은 코드 / 깨끗한 방법은 무엇입니까 4에서는 my_iter?

나는 이것을 할 수 있지만 그것은 매우 효율적이지 않은 것 같습니다.

[x for x in my_iter][-1]

item = defaultvalue
for item in my_iter:
    pass

deque크기 1을 사용하십시오 .

from collections import deque

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

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

Python 3.x를 사용하는 경우 :

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

Python 2.7을 사용하는 경우 :

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


주의 :

일반적으로 위에 제시된 솔루션은 일반적인 경우에 필요한 것이지만 대용량 데이터를 처리하는 경우 deque크기 1 을 사용하는 것이 더 효율적 입니다. ( source )

from collections import deque

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

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

__reversed__가능한 경우 사용할 가치가 있을 것입니다.

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

다음과 같이 간단합니다.

max(enumerate(the_iter))[1]

이것은 람다로 인해 빈 for 루프보다 빠를 것 같지 않지만 다른 사람에게 아이디어를 줄 수 있습니다.

reduce(lambda x,y:y,my_iter)

iter가 비어 있으면 TypeError가 발생합니다.


이거 있어요

list( the_iter )[-1]

반복의 길이가 정말 대단하다면 (너무 길어서 목록을 구체화하면 메모리가 고갈 될 것입니다) 디자인을 다시 생각해야합니다.


reversed다소 임의적으로 보이는 반복자 대신 시퀀스 만 사용 한다는 점을 제외하면을 사용 합니다.

어떤 식 으로든 전체 반복기를 실행해야합니다. 최대 효율에서 반복자가 다시 필요하지 않으면 모든 값을 폐기 할 수 있습니다.

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

그래도 이것이 차선책이라고 생각합니다.


툴들은의 라이브러리는 좋은 솔루션을 제공합니다 :

from toolz.itertoolz import last
last(values)

그러나 비 핵심 종속성을 추가하는 것은이 경우에만 사용할 가치가 없을 수 있습니다.


비슷한 코드를 보려면 다음 코드를 참조하십시오.

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

다음과 같이 마지막 항목을 선택하는 데 사용할 수 있습니다.

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

나는 그냥 사용합니다 next(reversed(myiter))


The question is about getting the last element of an iterator, but if your iterator is created by applying conditions to a sequence, then reversed can be used to find the "first" of a reversed sequence, only looking at the needed elements, by applying reverse to the sequence itself.

A contrived example,

>>> seq = list(range(10))
>>> last_even = next(_ for _ in reversed(seq) if _ % 2 == 0)
>>> last_even
8

Alternatively for infinite iterators you can use:

from itertools import islice 
last = list(islice(iterator(), 1000))[-1] # where 1000 is number of samples 

I thought it would be slower then deque but it's as fast and it's actually faster then for loop method ( somehow )


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.

참고URL : https://stackoverflow.com/questions/2138873/cleanest-way-to-get-last-item-from-python-iterator

반응형