(Please note that I hope to find a way that does not use list comprehension)
suppose I have the following data (0,1,2 indexes the row number and [[111,20,3,4], [5,66,7,8], [9,10,11,12]]
are the rows of an original matrix)
df1 = [(0, [111, 20, 3, 4]),
(1, [5, 66, 7, 8]),
(2, [9, 10, 11, 12])]
and I want to get the following output with 2 lambda functions inside a map function. it is of the format: (transposed_row_num, (original_row_num, value)) pairs for each row (for example, row is [111, 20, 3, 4]
etc.).
transposed_row_num is the column number of these rows. For example, 20 in row 0 has column number 1, so it should be (1,(0,20))
):
# Desired output:
[[(0, (0, 111)), (1, (0, 20)), (2, (0, 3)), (3, (0, 4))],
[(0, (1, 5)), (1, (1, 66)), (2, (1, 7)), (3, (1, 8))],
[(0, (2, 9)), (1, (2, 10)), (2, (2, 11)), (3, (2, 12))]]
I tried the following code, but I got an error:
map2 = map(lambda x: [x[0]] + list(map(lambda y: y[0], x[1].index(y))),
df1)
list(map2)
# ValueError: [[111, 20], [3, 4]] is not in list
you may do it with a nested list comprehension
that is more easy and the code is nicer
result = [
[(idx_in, (row[0], val)) for idx_in, val in enumerate(row[1])]
for row in df1
]
Then change the outer list comprehension
into a map
operation
result = list(map(lambda row: [(idx_in, (row[0], val)) for idx_in, val in enumerate(row[1])], df1))
Then change the inner list comprehension
into a map
operation
result = list(map(lambda row:
list(map(lambda idx_val: (idx_val[0], (row[0], idx_val[1])), enumerate(row[1]))), df1))