1

I have been trying to split and combine the following list without using any libraries like pandas.

Input list:

aa = [(('a', 'b', 'c'), 1), (('x', 'y', 'z'), 5), (('xa', 'ya', 'za'), 25)]

Expected output:

[('a', 'b', 'c', 1), ('x', 'y', 'z', 5), ('xa', 'ya', 'za', 25)]

I have already tried:

aa = [inner
    for outer in aa
       for inner in outer]

But it gave me:

[('a', 'b', 'c'), 1, ('x', 'y', 'z'), 5, ('xa', 'ya', 'za'), 25]

Which is close but not what I am looking for.

Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
James bond
  • 11
  • 3
  • 1
    Does this answer your question? [Flatten an irregular list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists) – Tomerikoo Aug 23 '21 at 12:05

4 Answers4

3
In [1]: aa = [(('a', 'b', 'c'), 1), (('x', 'y', 'z'), 5),(('xa', 'ya', 'za'), 25)]

In [2]: [(*i[0], i[1]) for i in aa]
Out[2]: [('a', 'b', 'c', 1), ('x', 'y', 'z', 5), ('xa', 'ya', 'za', 25)]

* operator unpacks tuple items.

pt12lol
  • 2,256
  • 1
  • 21
  • 46
1

You can try list comprehension

aa = [(('a', 'b', 'c'), 1), (('x', 'y', 'z'), 5),(('xa', 'ya', 'za'), 25)]

[(*i[0], i[1])for i in aa] #[('a', 'b', 'c', 1), ('x', 'y', 'z', 5), ('xa', 'ya', 'za', 25)]
Epsi95
  • 8,420
  • 1
  • 12
  • 30
0

Another solution without using the tuple unpacking is to use + operator between two tuples:

>>> [v[0]+(v[1],) for v in aa]
[('a', 'b', 'c', 1), ('x', 'y', 'z', 5), ('xa', 'ya', 'za', 25)]
ThePyGuy
  • 13,387
  • 4
  • 15
  • 42
0

You can try this:

aa = [(('a', 'b', 'c'), 1), (('x', 'y', 'z'), 5), (('xa', 'ya', 'za'), 25)]

aa = [x + (y,) for x,y in aa]
Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
Sanzid
  • 1
  • 1