Search code examples
pythonlisttuples

How to map element from one list to all elements in a sub-list to form a list of tuples (coordinates)


I am trying to map each element[x] from list: rows to all elements of the sub-list[x] from another list: cols and the result should be a list of tuples. These 2 lists, rows and cols have the same length, each element in rows will correspond to a sub-list(of various length) in list cols.

The output should be a list of tuples in which each tuple will have the elements mapped/zipped : (row[0], cols[0][0]), (row[0], cols[0][1]), (row[1], cols[1][0]) and so on...

Example input:

rows =  [502, 1064, 1500]
cols =  [[555, 905], [155, 475], [195, 595, 945]]

Desired output:

mapped = [(502, 555), (502, 905), (1064, 155), (1064, 475), (1500, 195), (1500, 595), (1500, 945)]

Solution

  • Try:

    rows = [502, 1064, 1500]
    cols = [[555, 905], [155, 475], [195, 595, 945]]
    
    out = []
    for r, c in zip(rows, cols):
        for v in c:
            out.append((r, v))
    
    print(out)
    

    Prints:

    [(502, 555), (502, 905), (1064, 155), (1064, 475), (1500, 195), (1500, 595), (1500, 945)]