Ashtart
Ashtart

Reputation: 131

Combining Tuples into a List

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?

Upvotes: 2

Views: 105

Answers (6)

cards
cards

Reputation: 4965

A version which respects the insertion order:

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

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

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

# flat list
l_flat = [i for pair in l for i in pair]

# dictionary of value-position pairs (1st occurence only)
d = dict.fromkeys(l_flat, None)
for i, v in enumerate(l_flat):
    if d[v] is not None:
        continue
    d[v] = i

# order per position and get values
res = [k for k, _ in sorted(d.items(), key=lambda p: p[1])]

# check result
print(res)

Upvotes: 0

Chris
Chris

Reputation: 36496

I strongly suggest you use a set comprehension to achieve this result. The set comprehension iterates over the tuples, then over the values in each tuple. We build a set from these values y.

a = [(1,2), (5,10), (2,5)]
{y for x in a 
   for y in x}
# {1, 2, 10, 5}

Upvotes: 0

TessellatingHeckler
TessellatingHeckler

Reputation: 28963

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.

Upvotes: 1

AmirMohammad Babaei
AmirMohammad Babaei

Reputation: 80

one-line solution:

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

Upvotes: 1

Adrian Ang
Adrian Ang

Reputation: 580

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]

Upvotes: 1

milkwithfish
milkwithfish

Reputation: 131

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))

Upvotes: 1

Related Questions