Sometimes an iterable might be not subscriptable. Say the return from itertools.permutations
:
ps = permutations(range(10), 10)
print ps[1000]
Python will complain that 'itertools.permutations' object is not subscriptable
Of course one can perform next()
by n
times to get the nth element. Just wondering are there better ways to do so?
Just use nth
recipe from 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)
A more readable solution is :
next(x for i,x in enumerate(ps) if i==1000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With