从对象列表中创建整数元素列表

时间:2013-07-31 13:39:11

标签: python

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

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

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

1 个答案:

答案 0 :(得分: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)查找,对于小型列表,您的方法也可以。

相关问题