Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I flatten just the inner list?

List:

results = [['04-25', [1, 2, 3, 4]], ['04-26', [5, 6, 7, 8]], ['04-27', [9, 20, 11, 21]]

Trying to get this output:

[['04-25', 1, 2, 3, 4], ['04-26', 5, 6, 7, 8], ['04-27', 9, 20, 11, 21]]

I have tried this:

data = [a for b in [_ for _ in results[i]] for a in b]

Which separates every character in the list into a different element, like this:

['0', '4', '-', '2', '5', 1, 2, 3, 4]

How do I access and flatten just the inner list?

like image 236
isopach Avatar asked Dec 08 '22 11:12

isopach


1 Answers

use * unpacking:

results = [['04-25', [1, 2, 3, 4]], ['04-26', [5, 6, 7, 8]], ['04-27', [9, 20, 11, 21]]]

data = [[a, *b] for a,b in results]

print(data)

Output:

[['04-25', 1, 2, 3, 4], ['04-26', 5, 6, 7, 8], ['04-27', 9, 20, 11, 21]]
like image 137
Adam.Er8 Avatar answered Dec 28 '22 07:12

Adam.Er8