Python: repeating elements in 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]

It works.

Now suppose the location object has a member of number_of_times. I want a list comprehension to generate n coordinate objects, where n is the number of ___ traces for a specific location. Therefore, if the location has number_of_times = 5, then the coordinates for this location will be repeated 5 times in the list. (This may be the case for the for loop, but I'm curious if this can be done using a list)

+3
source share
3 answers
coordinate_list = [x for location in locations
                   for x in [Coordinates(location.latitude,
                                         location.longitude)
                            ] * location.number_of_times]

: OP , , , , . :

coordinate_list = [ ]
for location in locations:
    coord = Coordinates(location.latitude, location.longitude)
    coordinate_list.extend([coord] * location.number_of_times)

, , extend , , Coordinate, .

+7

Try

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

number_of_times. , [1,2] * 3 [1, 2, 1, 2, 1, 2]. , , [, , ].

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

.

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

Source: https://habr.com/ru/post/1745720/


All Articles