1

我需要从对象列表中创建非重复整数元素列表。

例如:有一个对象有两个属性:'id'和'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]

有没有办法以更短的方式做到这一点?

4

1 回答 1

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)查找,对于小型列表,您的方法也可以。

于 2013-07-31T13:41:20.587 回答