Searching for most pythonic/least stupid way to do something simple

Michael Torrie torriem at gmail.com
Tue Mar 16 15:07:38 EDT 2010


david jensen wrote:
> of course, changing nn's to:
> def getOutcomes(myList=[2,5,8,3,5]):
>    low_id = int(myList[0]>myList[1])
>    amountToShare = 2*myList[low_id]
>    remainder = myList[not low_id]-myList[low_id]
>    tail=list(myList[2:])
>    outcomes = [[amountToShare*perc, remainder+amountToShare*(1-perc)]+
> tail for perc in (1.0, 0.75, 0.5, 0.25, 0.0)] if not low_id else
> [[remainder+amountToShare*perc, amountToShare*(1-perc)]+ tail for perc
> in (1.0, 0.75, 0.5, 0.25, 0.0)]
>    return outcomes
> 
> 
> works, just hides the ugliness in a more compact form

If Gerard's code works, I would consider it far superior to your code
here.  Pythonic does not necessarily mean short and ugly, nor does it
mean that you have to always use list comprehensions.   Having a
readable algorithm that's easy to follow in the future is a far better
way than trying to use python's cool features to compact the code to as
small and unreadable section as possible.

I used to use list comprehension all the time, but I've found that often
an explicit for loop is a much better solution in terms of
maintainability.  Especially when you start seeing nested comprehensions
such as you have here.




More information about the Python-list mailing list