NEWB: General purpose list iteration?

Peter Otten __peter__ at web.de
Fri Aug 12 02:56:58 EDT 2005


Donald Newcomb wrote:

> I was wondering it there's a simple routine (I
> think I can write a recurisve routine to do this.) to scan all the
> elements of a list, descending to lowest level and change something. What
> I'd like to do today is to convert everything from string to float. So, if
> I had a list of lists that looked like:
> [['1.1', '1.2', '1.3'], [['2.1', '2.2'], [['3.1', '3.2'], ['4.1',
> [['4.2']]]]
> and I'd like it to be:
> [[1.1, 1.2, 1.3], [[2.1, 2.2], [[3.1, 3,2], [4.1, 4.2]]]]
> is there just a library routine I can call to do this? Right now, I'm
> using 'for' loops nested to the maximum depth anticipated.

A non-recursive approach:

def enumerate_ex(items):
    stack = [(enumerate(items), items)]
    while stack:
        en, seq = stack[-1]
        for index, item in en:
            if isinstance(item, list):
                stack.append((enumerate(item), item))
                break
            yield index, seq[index], seq
        else:
            stack.pop()


data = [['1.1', '1.2', '1.3'], [['2.1', '2.2'], [['3.1', '3.2'], ['4.1',
'4.2']]]]

for index, value, items in enumerate_ex(data):
    items[index] = float(value)

# Now let's test the algorithm and our luck with float comparisons
assert data == [[1.1, 1.2, 1.3], [[2.1, 2.2], [[3.1, 3.2], [4.1, 4.2]]]]

Peter




More information about the Python-list mailing list