Type Hierarchies
Scottie
me at nospam.net
Thu Feb 15 01:13:34 EST 2001
Well, I'd suggest you think of what you mean by "flatten". It has the
same problem that something like "deepCopy" does: who knows when
you cross the boundary between interface and implementation.
If you have a list of numbers, and it turns out that my implementation
of rationals responds to "len," do you intend to iterate ove the interior
of my implementation? How about a new version of "long" which
allows access to the individual 16-bit elements of its representation?
I guess what I am saying is that "recurse through sequences and
sequence-like objects may be a surprisingly ill-defined operation.
-Scott David Daniels
Scott.Daniels at Acm.Org
"Burkhard Kloss" <bk at xk7.com> wrote in message
news:982164952.565065 at master.nyc.kbcfp.com...
> Thanks to all the people who reminded me that len() also works on mappings
> ...
>
> > def am_i_a_sequence(ob):
> > return type(ob) in
> > [types.StringType,types.ListType,types.TupleType,types.XRangeType]
>
> Yes, this works great for the built-in types - but not for user defined
> types, which is specifically what I'm after.
>
> > ['t','e','e','p']
> :)
>
> I guess concretely, the problem I'm trying to solve is iterating over a
> sequence which may contain sequences or items, e.g.
>
> [1, [2,3], 4, 5, [6,7,8,9]]
>
> and I was hoping to write something along the lines of
>
> for item in sequence:
> if is_sequence (item):
> for it in sequence:
> process (it)
> else:
> process (item)
>
> Which IMHO looks marginally cleaner than
>
> for item in sequence:
> try:
> for it in sequence:
> process (it)
> except:
> process (item)
>
> Although I guess what I should really do is
>
> for item in flatten(sequence):
> process (item)
>
> Hmmm.... now how do I effectively flatten a sequence ?
>
>
More information about the Python-list
mailing list