Home > Blockchain >  Combining Tuples into a List
Combining Tuples into a List

Time:08-21

I have a list of tuples:

[(1,2), (5,10), (2,5)]

And I would like to get a list of unique numbers

[1,2,5,10]

May I know how can I achieve that?

CodePudding user response:

You can use numpy to do it this way:

import numpy as np

x = [(1,2),(5,10),(2,5)]
result = np.array(x).reshape(-1)

If you want to get unique values, use set() like this:

result = set(np.array(x).reshape(-1))

CodePudding user response:

import itertools

L = [(1,2), (5,10), (2,5)]

flat_no_dupes = set(itertools.chain.from_iterable(L))

Using itertools chain from iterable to flatten the list, and making a set to remove duplicates.

CodePudding user response:

Will this work? I've appended each item to a new list, then use set() to get the unique items

new_lis = []
lis = [(1,2),(5,10),(2,5)]
for x,y in lis:
    new_lis.append(x)
    new_lis.append(y)
    
result = list(set(new_lis))

[1, 2, 10, 5]

CodePudding user response:

one-line solution:

tuples_list = [(1,2), (5,10), (2,5)]
res = sorted(list(set(sum(tuples_list, ()))))
  • Related