2010-05-17 81 views
3

我有以下的列表理解,它返回每个位置的坐标对象列表。Python:在列表理解中重复元素?

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

这工作。

现在假设位置对象有一个number_of_times成员。我想要一个列表理解来生成n个坐标对象,其中n是特定位置的number_of_times。因此,如果一个位置的number_of_times = 5,那么该位置的坐标将在列表中重复5次。 (也许这是for循环的情况,但我很好奇,如果它可以通过列表解析完成)

回答

7
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比如你正在扩大用。

+1

您还应该指出,当坐标旨在成为可变对象时,这会产生问题。 – 2010-05-17 11:27:13

+0

其实蚂蚁的评论让我选择这个作为答案。这个答案比我更喜欢,因为它使用了我认为使用较少内存的相同坐标对象。在这种情况下,坐标对象不会被改变。 – User 2010-05-19 05:11:48

+0

风格问题:将它作为for循环写入会更可取吗?理解过于复杂,难以阅读? – User 2010-05-19 05:24:07

0

您可以乘以number_of_times值的序列。所以[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 

连接coordsFor列表中的每个元素。

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

他想要在不同的时间重复个别元素。 – 2010-05-17 03:50:19

+0

是的,我提交后才意识到。相应地更正了我的答复。 – Ishpeck 2010-05-17 04:04:00

6

尝试

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

我建议'xrange'(迭代器)而不是'range'(列表) – 2010-05-17 04:59:35

+0

当我将它与我选择的答案进行比较时,我不能通过阅读理解来告诉他们所做的不同。我实际上不得不写一个测试程序来看看有什么不同。这个为列表中的每个项目创建唯一的坐标对象,而另一个重复使用同一个坐标对象作为重复坐标。有趣。 – User 2010-05-19 05:14:59

+0

Python 2.x的'xrange',Python 3.x的''range'。 – eksortso 2010-05-19 16:48:38