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?
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}
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]
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.