2012-08-17 6 views
17

Czasami wartość iteracji może nie być indeksowana. Twierdzą, że powrót z itertools.permutations:Lepsze sposoby na uzyskanie n-tego elementu z niepublikowanej iterable

ps = permutations(range(10), 10) 
print ps[1000] 

Python skarżą się, że 'itertools.permutations' object is not subscriptable

Oczywiście można wykonać next() autorem n razy, aby uzyskać n-ty element. Zastanawiasz się, czy są na to lepsze sposoby?

+1

lepsze pod względem czego? wydajność lub przestrzeń. –

+1

w sposób python. – clwen

Odpowiedz

24

Wystarczy użyć nth receptury z itertools

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

>>> print nth(permutations(range(10), 10), 1000) 
(0, 1, 2, 4, 6, 5, 8, 9, 3, 7) 
+2

To jest piękna rzecz. (+1) – mgilson

Powiązane problemy