2013-07-31 118 views
1

我需要從對象列表創建非重複整數元素列表。根據對象列表創建整數元素列表

例如: 有兩個屬性的對象:「身份證」和「other_id」:

first = [elem.id for elem in objects_list] 
second = [elem.other_id for elem in objects_list] 
print first 
[0,1,2,3,4,5] 
print second 
[4,5,6,7,9] 

現在我可以創建一個包含兩個列表,從所有對象的兩個屬性是這樣的:

first = [elem.id for elem in objects_list] 
first.extend(elem.other_id for elem in objects_list if elem.other_id not in first) 
print first 
[0,1,2,3,4,5,6,7,9] 

有什麼辦法可以做到這一點嗎?

回答

1

使用set

sorted(set().union(first, second)) #returns a sorted list of unique items 

演示:

>>> first = [0,1,2,3,4,5] 
>>> second = [4,5,6,7,9] 
>>> sorted(set(first + second)) 
[0, 1, 2, 3, 4, 5, 6, 7, 9] 

如果原來的順序事項:

>>> first = [0,1,2,3,4,5] 
>>> seen = set(first) 
>>> first += [x for x in second if x not in seen and not seen.add(x)] 
>>> first 
[0, 1, 2, 3, 4, 5, 6, 7, 9] 

對於大名單的設置方法將是有效的作爲集提供O(1)查找,對於小列表,你的方法也沒關係。

+0

「+」列表的替代方法是使用'set()。union(first,second)' –

+0

@JonClements好主意,那更好。 –