Python:在列表中重复元素?

Python:在列表中重复元素?,python,list-comprehension,Python,List Comprehension,我有下面的列表,它返回每个位置的坐标对象列表 coordinate_list = [Coordinates(location.latitude, location.longitude) for location in locations] 这很有效 现在假设location对象有一个数量为的成员。我需要一个列表来生成n个坐标对象,其中n是特定位置的次数。因此,如果一个位置的次数为5,那么该位置的坐标将在列表中重复5次。(这可能是for循环的一种情况,但我很

我有下面的列表,它返回每个位置的坐标对象列表

coordinate_list = [Coordinates(location.latitude, location.longitude)
                   for location in locations]
这很有效


现在假设location对象有一个数量为的成员。我需要一个列表来生成n个坐标对象,其中n是特定位置的次数。因此,如果一个位置的次数为5,那么该位置的坐标将在列表中重复5次。(这可能是for循环的一种情况,但我很好奇它是否可以通过列表理解来实现)

您可以将一个序列乘以
次数的值。所以[1,2]*3等于[1,2,1,2,1,2]。如果在列表中获得坐标,然后将列表乘以重复次数,结果应为[coord,coord,coord]

def coordsFor(location):
   return coord = [Coordinates(location.latitude, location.longitude) ]*location.number_of_times
连接列表中每个元素的坐标

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

编辑:OP建议循环可能更清晰,考虑到标识符的长度,这肯定是一种可能性。然后,等效代码将类似于:

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

循环看起来不错,部分原因是列表的
extend
方法在这里工作得很好,部分原因是您可以为扩展的
Coordinate
实例命名。

他想在不同的时间重复各个元素。是的,我在提交后就意识到了这一点。相应地更正了我的回答。我建议使用
xrange
(迭代器)而不是
range
(列表)。当我将其与我选择的答案进行比较时,我无法通过阅读理解说明它们有什么不同。事实上,我必须编写一个测试程序,看看有什么不同。这一个为列表中的每个项目创建唯一的坐标对象,而另一个为重复的坐标重用相同的坐标对象。有趣。
xrange
对于Python2.x,对于Python3.x,
range
对于@User,您如何区分唯一坐标对象和重用坐标对象?当调用__; repr __;时,它以十六进制显示内存位置(我认为),通过您的解决方案,我可以看到每个坐标对象都有一个唯一的内存位置,使用另一种解决方案,我可以看到重复的坐标对象共享相同的内存位置。您还应该指出,当坐标是可变对象时,这会出现问题。事实上,我选择了这个作为答案。这个答案对我来说更可取,因为它使用相同的坐标对象,我假设使用更少的内存。在这种情况下,坐标对象将不会更改。样式问题:是否最好将其作为for循环编写?理解是否太复杂而不容易阅读?@User,这并不复杂,但标识符的长度会造成伤害--
[pts中的c代表p,pts中的c代表c[Coord(p.x,p.y)]*p.N]
(相同的结构,较短的名称)也可以,但名称的长度足以迫使代码占用3-4行,这使得解析变得更加困难。因此,编辑以显示备选方案。
coordinate_list = [x for location in locations
                   for x in [Coordinates(location.latitude,
                                         location.longitude)
                            ] * location.number_of_times]
coordinate_list = [ ]
for location in locations:
    coord = Coordinates(location.latitude, location.longitude)
    coordinate_list.extend([coord] * location.number_of_times)