Reputation: 10979
From this data structure: [(1,2),(1,3),(1,4),(1,5)]
I am tying to get the unique values, or [1,2,3,4,5]
. What's the easy solution here?
Upvotes: 1
Views: 802
Reputation: 21619
Use chain.from_iterable
from the itertools
module. It's generally considered to be the idiomatic way to flatten a 2D iterable as opposed to a nested list comprehension. See this question.
>>> from itertools import chain
>>> set(chain.from_iterable([(1,2),(1,3),(1,4),(1,5)]))
{1, 2, 3, 4, 5}
chain.from_iterable
flattens the list and set
keeps only unique values.
To convert back to a list, simply pass to the list
constructor.
>>>list(set(chain.from_iterable([(1,2),(1,3),(1,4),(1,5)])))
[1, 2, 3, 4, 5]
Upvotes: 2
Reputation: 152850
In your expected output the order of the unique elements follows the order of appearance. One way to do it would be (using an external library but the recipes are avaiable in the itertools
-recipes section):
>>> from iteration_utilities import flatten, unique_everseen
>>> x = [(1,2),(1,3),(1,4),(1,5)]
>>> list(unique_everseen(flatten(x)))
[1, 2, 3, 4, 5]
Upvotes: 0
Reputation: 215127
You can use set
with list comprehension:
lst = [(1,2),(1,3),(1,4),(1,5)]
set(j for i in lst for j in i)
# {1, 2, 3, 4, 5}
Upvotes: 5