Arrays/List, filters, Pytho, Ruby
Bruno Piguet
bruno.piguet at gmail.com
Sat Feb 12 08:06:49 CET 2011
On 11 fév, 22:24, "LL.Snark" <ll.sn... at gmail.com> wrote:
> Hi,
>
> I'm looking for a pythonic way to translate this short Ruby code :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=t.index {|x| x<t.first}
I'm thinking of two methods, depending on the length of the list, and
the fact that you wish (or not) to scan the whole list.
The first one, quite simple, but scanning the whole list :
t=[6,7,8,6,7,9,8,4,3,6,7]
[x<t[0] for x in t].index(True)
The alternative method, which will stop at the first element matching
the condition, but which might be less readable :
next(i for i, x in enumerate(t) if x<t[0])
If there is a risk that no element match the condition, and you don't
want an StopIteration exception, use the second optionnal argument of
next :
next((i for i, x in enumerate(t) if x>1000), "not found")
or
next((i for i, x in enumerate(t) if x>1000), None)
or whatever matches your needs.
Note that if you use the second optionnal argument of next, you'll
need an additional pair of parentheses around
the generator expression which is the first argument of next.
Bruno.
More information about the Python-list
mailing list