2

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?

blackraven
  • 5,284
  • 7
  • 19
  • 45
Ashtart
  • 121
  • 5

6 Answers6

1

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))
milkwithfish
  • 141
  • 3
1

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]
Adrian Ang
  • 520
  • 5
  • 12
1

one-line solution:

tuples_list = [(1,2), (5,10), (2,5)]
res = sorted(list(set(sum(tuples_list, ()))))
  • `sum( , ())` is not designed to chain iterables, see doc – cards Sep 04 '22 at 00:21
  • ...and `sorted` is nonsense: with `[(5,10),(2,5), (1,2)]` you get the same result. The order of insertion should be respected – cards Sep 04 '22 at 00:34
1
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.

TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
0

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}
Chris
  • 26,361
  • 5
  • 21
  • 42
0

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)
cards
  • 3,936
  • 1
  • 7
  • 25