User
User

Reputation: 66081

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)

Upvotes: 4

Views: 4307

Answers (3)

Alex Martelli
Alex Martelli

Reputation: 882681

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.

Upvotes: 7

Ishpeck
Ishpeck

Reputation: 2041

You can multiply a sequence by the number_of_times value. So [1,2]*3 will equal [1, 2, 1, 2, 1, 2] . If you get your coordinates in a list then multiply the list by the number of repeats, your result should be [coord, coord, coord].

def coordsFor(location):
   return coord = [Coordinates(location.latitude, location.longitude) ]*location.number_of_times

Concatenate the coordsFor of each element in the list.

reduce(operator.add, map(coordsFor, locations), [])

Upvotes: 0

brainjam
brainjam

Reputation: 19005

Try

coordinate_list = [Coordinates(location.latitude, location.longitude)
                   for location in locations 
                   for i in range(location.number_of_times)]

Upvotes: 6

Related Questions