python - Create a list of integer elements from list of objects -
i need create list of non-duplicated integer elements list of objects.
for example: there object 2 attributes: 'id' , 'other_id':
first = [elem.id elem in objects_list] second = [elem.other_id elem in objects_list] print first [0,1,2,3,4,5] print second [4,5,6,7,9]
now can create 2 list containing 2 attributes objects this:
first = [elem.id elem in objects_list] first.extend(elem.other_id elem in objects_list if elem.other_id not in first) print first [0,1,2,3,4,5,6,7,9]
is there way in shorter way?
use set
:
sorted(set().union(first, second)) #returns sorted list of unique items
demo:
>>> 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]
if original order matters:
>>> first = [0,1,2,3,4,5] >>> seen = set(first) >>> first += [x x in second if x not in seen , not seen.add(x)] >>> first [0, 1, 2, 3, 4, 5, 6, 7, 9]
for large lists set approach going efficient sets provide o(1)
lookup, tiny lists approach okay.
Comments
Post a Comment