Can a List Comprehension do ____ ?

Steve lonetwin at gmail.com
Wed Jul 14 04:01:41 EDT 2004


Hi Eric,

> Can anyone show me the List Comprehensions light?

Before the answer to your question, I'd like to explain how I think
about List Comprehensions, please bear with me ...if you can't be
bothered, look at the solution at the end of my message.

   Well, here's how i think about it: 
- given a sequence "L"
- return me a list --------> []
- containing the result of a operation y --------> [ y() ]
- for every element i, in the list L --------> [ y(i) for i in L]
- or for every element i, in the list L that evaluates true for condition x
     --------> [ y(i) for i in L if x(i) == True ]

Now your specific problem, this is my line of thought (maybe not the
best way to do this ...but it's mine anyways).
    The problem does not deal with every element of the L, rather, it
deals with every element *and* it's successive element. So, to do this
with LC's we need to realize a few things,
a) We need to iterate over the L, knowing the index of the element we
are iterating over.
b) We need to be aware that we will get the expected result only for
lists with even number of elements, since with an odd numbered list
with 'n' elements, we do not have a successive element (ie: the n+1th)
c) We need to know when we have reached the end of the list.

so the LC is:
a) return a list :
        []
b) iterating over every element in 'breaks', using it's index:
        [ for i in range(len(breaks)) ]
c) and return the max() of the i'th element and the min() of it's
successive element:
        [ (max(b[i]), min(b[i+1])) for i in range(len(breaks)) ]
d) remembering that there would be no successive element for the last
element in the list:
        [ (max(b[i]), min(b[i+1])) for i in range(len(breaks)) if i+1
< len(breaks) ]

HTH
Steve



More information about the Python-list mailing list