Basel Shishani
Basel Shishani

Reputation: 8197

Create a list of tuples from two nested lists

Having a list A with an arbitrary degree of nesting, and a list B with a nesting structure equivalent to that of A (or deeper), how can we create a list of tuples for all corresponding elements? For example:

A = ['a', ['b', ['c', 'd']], 'e'] 
B = [1, [2, [3, [4, 5]]], 6]
>>>
[('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]

Upvotes: 1

Views: 452

Answers (5)

namit
namit

Reputation: 6957

In [3]: from compiler.ast import flatten

In [4]: zip(flatten(A), flatten(B))
Out[4]: [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239693

Basically, all you need to do is, iterate a and b simultaneously and return the values of a and b, if the current element of a is not a list. Since your structure is nested, we can't lineraly iterate them. That is why we use recursion.

This solution assumes that there is always an corresponding element in B for every element in A.

def rec(a, b):
    if isinstance(a, list):
        # If `a` is a list
        for index, item in enumerate(a):
            # then recursively iterate it
            for items in rec(item, b[index]):
                yield items
    else:
        # If `a` is not a list, just yield the current `a` and `b`
        yield a, b

print(list(rec(['a', ['b', ['c', 'd']], 'e'], [1, [2, [3, [4, 5]]], 6])))
# [('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]

Upvotes: 3

ylsun
ylsun

Reputation: 31

you can use zip, this is my answer.

a = ['a', ['b', ['c', 'd']], 'e']
b = [1, [2, [3, [4, 5]]], 6]
c = []

def CheckIfList(a):
    for k in a:
        print 'k is:', k
        if isinstance(k, (list, tuple)):
            return True
    return False

def ZipAllElements(a, b, c):
    if CheckIfList(a):
        r = zip(a, b)
        for i in r:
            if isinstance(i[0], (list, tuple)):
                ZipAllElements(i[0], i[1], c)
            else:
                c.append(i)
    else:
        c.extend(list(zip(a, b)))

ZipAllElements(a, b, c)
print c

Upvotes: 0

Shashank Agarwal
Shashank Agarwal

Reputation: 2804

You can iterate with zip to create a list,

A = ['a', ['b', ['c', 'd']], 'e'] 
B = [1, [2, [3, [4, 5]]], 6]

def make_tuples(list1, list2):
    tups = []
    def _helper(l1, l2):
        for a, b in zip(l1, l2):
            if isinstance(a, list) and isinstance(b, list):
                _helper(a, b)
            else:
                tups.append((a, b))
    _helper(list1, list2)
    return tups

make_tuples(A, B)

Or a simple tuples generator -

def tuples_generator(l1, l2):
    for a, b in zip(l1, l2):
        if isinstance(a, list) and isinstance(b, list):
            tuples_generator(a, b)
        else:
            yield (a, b)

In : make_tuples(A, B)
Out: [('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]

Upvotes: 1

mgilson
mgilson

Reputation: 310307

You want a recursive zip function:

from itertools import izip
def recurse_zip(a, b):
    zipped = izip(a, b)
    for t in zipped:
        if isinstance(t[0], list):
            for item in recurse_zip(*t):
                yield item
        else:
            yield t

Demo:

>>> A = ['a', ['b', ['c', 'd']], 'e'] 
>>> B = [1, [2, [3, [4, 5]]], 6]
>>> print(list(recurse_zip(A, B)))
[('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]

Notes:

  • izip is helpful to make it lazy -- python3.x's zip would work just as well.
  • Can use yield from syntax in python3.3+ (yield from recurse_zip(*t)).
  • Generators are awesome.

Upvotes: 2

Related Questions