Am1rr3zA
Am1rr3zA

Reputation: 7421

recursively (or non-recursively) iterating through python array and get the elements

I have a python array data-structure like [[v], [v]] that v is an array of size 2 or another [[v],[v]] data type. you can see the real data below:

ex1:

list: [[[1, '1.0.1'], [1, '2.0.1']], [1, '3.0.11']]

ex2:

list: [[[[1, '1.0.1'], [1, '2.0.1']], [1, '3.0.11']], [1, '4.0.11']]

now my problem is that I should get elements from left to right first [1, '1.0.1'] then [1, '2.0.1'] and so on. and note that the size of array vary.

how can I achieve this?

Upvotes: 1

Views: 2108

Answers (3)

Óscar López
Óscar López

Reputation: 236114

One possible solution would be to flatten the list:

def flatten(lst):
    if not lst:
        return []
    elif not isinstance(lst, list):
        return [lst] 
    else:
        return flatten(lst[0]) + flatten(lst[1:])

This will allow you to traverse the list in order:

ls1 = [[[[1, '1.0.1'], [1, '2.0.1']], [1, '3.0.11']], [1, '4.0.11']]
flatten(ls1)
=> [1, '1.0.1', 1, '2.0.1', 1, '3.0.11', 1, '4.0.11']

Or alternatively, using generators:

def flatten(lst):
    if not lst:
        return
    elif not isinstance(lst, list):
        yield lst
    else:
        for e in flatten(lst[0]):
            yield e
        for e in flatten(lst[1:]):
            yield e

list(flatten(ls1))
=> [1, '1.0.1', 1, '2.0.1', 1, '3.0.11', 1, '4.0.11']

Upvotes: 3

simonzack
simonzack

Reputation: 20938

Here's an iterator to do what you want:

def iterate(xs):
    try:
        if isinstance(xs[1],str):
            yield xs
            return
    except IndexError:
        pass
    for x in xs:
        yield from iterate(x)

Example usage:

>>> list(iterate([[[[1, '1.0.1'], [1, '2.0.1']], [1, '3.0.11']], [1, '4.0.11']]))
[[1, '1.0.1'], [1, '2.0.1'], [1, '3.0.11'], [1, '4.0.11']]

Upvotes: 1

Paul Becotte
Paul Becotte

Reputation: 9997

This answer is probably missing something obvious, so I apologize in advance...

But your data structure seems to be a lot more complicated than it needs to be?

Would

v = [(1, '1.0.1'), (1, '2.0.1'), (1, '3.0.11')]
v.append((1, '4.0.11'))
print v

do what you want?

Upvotes: 0

Related Questions