advanced listcomprehenions?

MRAB google at mrabarnett.plus.com
Wed Jun 18 19:29:50 EDT 2008


On Jun 18, 10:42 pm, cirfu <circularf... at yahoo.se> wrote:
> I am wondering if it is possible to write advanced listcomprehensions.
>
> For example:
> """Write a program that prints the numbers from 1 to 100. But for
> multiples of three print "Fizz" instead of the number and for the
> multiples of five print "Buzz". For numbers which are multiples of
> both three and five print "FizzBuzz"."""
> Obv it doesnt have to be a list according tot hat definition but
> suppose i want to generate that list.
>
> >>> [["Fizzbuzz",x] for x in xrange(1,101) if x%3 == 0 and x%5 == 0]
>
> [['Fizzbuzz', 15], ['Fizzbuzz', 30], ['Fizzbuzz', 45], ['Fizzbuzz',
> 60], ['Fizzbuzz', 75], ['Fizzbuzz', 90]]
>
> is not what i want. the following does the trick but is ldo not a
> listcomprehension:
>
> for i in xrange(1,101):
>     s = ""
>     if i%3 == 0:
>         s += "Fizz"
>     if i%5 == 0:
>         s += "Buzz"
>     if s:
>         print "%d : %s" % (i,s)
>     else:
>         print i
>
> or to generate a lisrt but not by listcomprehsnion:
> map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and
> "Fizz")
> or (not x%5 and "Buzz") or x, xrange(1,101))

[("FizzBuzz" if n % 15 == 0 else "Fizz" if n % 3 == 0 else "Buzz" if n
% 5 == 0 else str(n)) for n in range(1, 101)]



More information about the Python-list mailing list