2

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?

  • Does this answer your question? [List comprehension on a nested list?](https://stackoverflow.com/questions/18072759/list-comprehension-on-a-nested-list) – Tomerikoo Aug 23 '21 at 13:24

5 Answers5

2

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]]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
2

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 ]
Craig
  • 4,605
  • 1
  • 18
  • 28
  • 2
    Yep! Indeed it's probably more correct to model these as tuples, since it appears to be an ordered pair. `data = [('60', '01'), ('30', '19')]; coords = [(int(a), int(b)/60) for a,b in coords]` – Adam Smith Aug 23 '21 at 03:54
  • 2
    @AdamSmith - I agree. The only reason that these are lists is to match the output requested by the OP. – Craig Aug 23 '21 at 03:57
1

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]]
1
[[int(j)/60**idx for idx, j in enumerate(i)] for i in coords]
[[60.0, 0.016666666666666666], [30.0, 0.31666666666666665]]
Epsi95
  • 8,832
  • 1
  • 16
  • 34
1
[
 [int(element)/60**i for i, element in enumerate(sublist)]
     for sublist in coords
]
Acccumulation
  • 3,491
  • 1
  • 8
  • 12