I have the following list comprehension which returns a list of coordinate objects for each location.
coordinate_list = [Coordinates(location.latitude, location.longitude)
for location in locations]
This works.
Now suppose the location object has a number_of_times member. I want a list comprehension to generate n Coordinate objects where n is the number_of_times for the particular location. So if a location has number_of_times = 5 then the coordinates for that location will be repeated 5 times in the list. (Maybe this is a case for a for-loop but I'm curious if it can be done via list comprehensions)
coordinate_list = [x for location in locations
for x in [Coordinates(location.latitude,
location.longitude)
] * location.number_of_times]
Edit: the OP suggests a loop may be clearer, which, given the length of the identifiers, is definitely a possibility. The equivalent code would then be something like:
coordinate_list = [ ]
for location in locations:
coord = Coordinates(location.latitude, location.longitude)
coordinate_list.extend([coord] * location.number_of_times)
The loop does look fine, partly because the extend
method of lists works nicely here, and partly because you get to give a name to the Coordinate
instance you're extending with.
Try
coordinate_list = [Coordinates(location.latitude, location.longitude)
for location in locations
for i in range(location.number_of_times)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With