2010-05-17 25 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