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

Question:

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…

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, 959), (1500, 945)]

thanks!

Asked By: mod13

||

Answers:

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)]
Answered By: Andrej Kesely

Code: [List Comprehension]

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

mapped = [(row, col) for row, nested_col in zip(rows, cols) for col in nested_col]

print(mapped)

Output:

[(502, 555), (502, 905), (1064, 155), (1064, 475), (1500, 195), (1500, 595), (1500, 945)]
Answered By: Yash Mehta