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
  • 18,379
  • 16
  • 47
  • 61
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,332
  • 1
  • 22
  • 48
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,832
  • 1
  • 16
  • 34
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
  • 17,779
  • 5
  • 18
  • 45
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
  • 18,379
  • 16
  • 47
  • 61
Sanzid
  • 11
  • 3