Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Repeat elements in a list comprehension?

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)

like image 800
User Avatar asked Dec 12 '22 21:12

User


2 Answers

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.

like image 98
Alex Martelli Avatar answered Dec 26 '22 19:12

Alex Martelli


Try

coordinate_list = [Coordinates(location.latitude, location.longitude)
                   for location in locations 
                   for i in range(location.number_of_times)]
like image 25
brainjam Avatar answered Dec 26 '22 18:12

brainjam