mod13
mod13

Reputation: 25

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)]

Upvotes: 0

Views: 61

Answers (2)

Yash Mehta
Yash Mehta

Reputation: 2006

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)]

Upvotes: 2

Andrej Kesely
Andrej Kesely

Reputation: 195543

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)]

Upvotes: 1

Related Questions