two little syntax questions

Alex Martelli aleax at aleax.it
Thu Aug 30 10:17:58 EDT 2001


"Marcus Stojek" <stojek at part-gmbh.de> wrote in message
news:MPG.15f85254d2e52b09989684 at news.easynews.net...
> Hi,
>
> Two little syntax questions:
> 1.-----------------------------
> I have a huge dict of 3-tuples. I need the min and max value
> of all tuple[0] entries.
>
> I would like to use reduce. Something like:
>
> nodes[1]=(3,2,5)
> nodes[2]=(-1,2,9)
> nodes[3]=(0,1,6)
> nodes[4]=(2,9,1)
>
> minx = reduce(lambda a,b:min(a,b),nodes???and now what)

I would (as usual) avoid lambda in favour of a "local"
(possibly nested) function -- so you can name it, etc:

def lowtup(previous_lowest, and_a_tuple):
    return min(previous_lowest, and_a_tuple[0])
minx = reduce(lowtup, nodes.values(), nodes[1][0])

It's unusual to have reduce use a function that takes
two *different* types of arguments, but it's OK as
long as:
    -- the function returns a value that's of the
        same type it wants as a first argument,
    -- you call reduce in the 3-argument form, and
        the 3rd argument is OK as a first argument
        to the function you're reducing with.

Note that you need a separate def for the function
used to compute the maxx.

Of course, all of the complications come from your
desire to use reduce -- it's much simpler and much
faster to use min and max directly:

first_items = [x[0] for x in nodes.values()]
minx = min(first_items)
maxx = min(first_items)

> how do I explain: take first entry in tuple for all keyvalues

See the expression I use above for first_items -- it's
a list-comprehension doing just this (except it uses
values, not keys -- keys seem to have nothing to do
with the case, judging from your example).


> 2.------------------------------
>
> I have to print the remaining entries of a list
> (first entries are printed in groups of 8 per line)
>
> lines = len(list)/8
> rest = len(list)%8
> print rest * "i," % (list[lines*8:])
>
> doesn't work. Okay I know print is expecting a tuple and
> list[lines*8:] is not. So how can I transform this into
> a tuple.

I think what you're looking for may be something like:

    if rest: print (rest*"%i ")%tuple(list[-rest:])


Alex






More information about the Python-list mailing list