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!
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')]]
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')]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With