You can also do it in a more pythonic way but without generators :
# a = [[1,5,2], 8, 4]
# l = []
# for item in a:
#if isinstance(item, (int, long)):
#l.append(item)
#else:
#l+=item
# print dict([(item,i+1) for (i,item) in enumerate(l)])
It works in the same conditions as yo
What's "LBYL"? Oh...Look-before-you-leap. OK.
I think I understand what's going on now (I read up on generator and
iterators and my head still hurts). I knew there must be a cleaner way of
"walking" around in Python. I will experiment with generator more.
Thanks everybody.
"Jp Calderone" <[
On Tue, 04 Jan 2005 08:18:58 -0800, Scott David Daniels <[EMAIL PROTECTED]>
wrote:
>Nick Coghlan wrote:
> > A custom generator will do nicely:
> >
> > Py> def flatten(seq):
> > ... for x in seq:
> > ... if hasattr(x, "__iter__"):
> > ... for y in flatten(x):
> > ... yield y
Nick Coghlan wrote:
A custom generator will do nicely:
Py> def flatten(seq):
... for x in seq:
... if hasattr(x, "__iter__"):
... for y in flatten(x):
... yield y
... else:
... yield x
Avoiding LBYL gives you:
def flatten(seq):
for x in seq:
try
Thanks, Steve and Nick.
Yes, that's what I need to do. I didn't know it's call "flattening" a list
structure but that's precisely what I needed to do.
Steve,
I am using 2.3 and so I will go with Nick's version.
Thanks to both for helping.
"Nick Coghlan" <[EMAIL PROTECTED]> wrote in message
It's me wrote:
Another newbie question.
There must be a cleaner way to do this in Python:
section of C looking Python code
a = [[1,5,2], 8, 4]
a_list = {}
i = 0
for x in a:
if isinstance(x, (int, long)):
x = [x,]
for w in [y for y in x]:
i = i + 1
a_list[w]
It's me wrote:
Another newbie question.
There must be a cleaner way to do this in Python:
section of C looking Python code
a = [[1,5,2], 8, 4]
a_list = {}
i = 0
for x in a:
if isinstance(x, (int, long)):
x = [x,]
for w in [y for y in x]:
i = i + 1
a_list[w]