Python - stuck with correct list assignment

Viewed 81

Here's the thing:

coords = [['60', '01'], ['30', '19']]
coords = [int(coords[i][j])/60**j for i in range(2) for j in range(len(coords[i]))]

Expected output:

>>>[[60.0, 0.016666666666666666], [30.0, 0.31666666666666665]]

What i've got:

>>>[60.0, 0.016666666666666666, 30.0, 0.31666666666666665]

Gimme a hint: how to assign values through list comprehension in a desired way?

5 Answers

Try switching the order of the for loops and add brackets:

coords = [[int(coords[i][j])/60**j for j in range(len(coords[i]))] for i in range(2)]
print(coords)

Output:

[[60.0, 0.016666666666666666], [30.0, 0.31666666666666665]]

Since you've hard-coded the value 2 as the length of the inner arrays, you could use a simpler comprehension:

coords = [[int(a), int(b)/60] for a,b in coords ]

You can move the second for loop and enclose it in brackets:

coords = [[int(coords[i][j])/60**j for j in range(len(coords[i]))] for i in range(2) ]

Output:

[[60.0, 0.016666666666666666], [30.0, 0.31666666666666665]]
[[int(j)/60**idx for idx, j in enumerate(i)] for i in coords]
[[60.0, 0.016666666666666666], [30.0, 0.31666666666666665]]
[
 [int(element)/60**i for i, element in enumerate(sublist)]
     for sublist in coords
]
Related