Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested structure: List of lists of tuples python

I am trying to deal with a nested structure that looks like this:

list_of_lists= [[("aaa"),("bbb")],[("ccc"),("ddd")],[("eee"),("fff")]]

and I need to add a column of elements that looks like this:

 column_to_add = ["string1", "string2", "string3"]

The final result should look like this:

[[("aaa", "string1"),("bbb", "string1")],[("ccc", "string2"),("ddd", "string2")],[("eee", "string3"),("fff", "string3")]]

I have tried something like this:

result= []
for internal_list in list_of_lists:
    for tuple in internal_list:
        for z in tuple:
            for new_string in column_to_add:
                kk=list(tuple)
                result = tuple.append(new_string)

But it does not seem to work at all. Can anyone help me?

Thanks so much in advance!

like image 732
iraciv94 Avatar asked Dec 10 '22 03:12

iraciv94


2 Answers

If your data looks like this:

list_of_lists= [[("aaa", ),("bbb", )],[("ccc", ),("ddd", )],[("eee", ),("fff", )]]

You should use:

[[y + (column_to_add[i], ) for y in x] for i, x in enumerate(list_of_lists)]

This produces:

#[[('aaa', 'string1'), ('bbb', 'string1')],
# [('ccc', 'string2'), ('ddd', 'string2')],
# [('eee', 'string3'), ('fff', 'string3')]]
like image 102
zipa Avatar answered Dec 22 '22 00:12

zipa


Using zip and a nested list comprehension

Ex:

list_of_lists= [[("aaa"),("bbb")],[("ccc"),("ddd")],[("eee"),("fff")]]
column_to_add = ["string1", "string2", "string3"]

print([[(i, n) for i in m] for m,n in zip(list_of_lists, column_to_add)])

Output:

[[('aaa', 'string1'), ('bbb', 'string1')],
 [('ccc', 'string2'), ('ddd', 'string2')],
 [('eee', 'string3'), ('fff', 'string3')]]
like image 42
Rakesh Avatar answered Dec 22 '22 00:12

Rakesh