1

I have a nested list which looks like this:

l = [[['0.056*"googl"'], ['0.035*"facebook"']], #Index 0
 [['0.021*"mensch"'], ['0.012*"forsch"']], #Index 1
 [['0.112*"appl"'], ['0.029*"app"']], # Index 2
 [['0.015*"intel"'], ['0.015*"usb"']]] #Index 3

Now I want to append the Index (and the word Topic) of the sublists into the individual sublists like this:

nl = [[['0.056*"googl"', 'Topic 0'], ['0.035*"facebook"', 'Topic 0']], 
 [['0.021*"mensch"', 'Topic 1'], ['0.012*"forsch"', 'Topic 1']], 
 [['0.112*"appl"', 'Topic 2'], ['0.029*"app"', 'Topic 2']], 
 [['0.015*"intel"', 'Topic 3'], ['0.015*"usb"', 'Topic 3']]]

How can I do this?

asked Jan 28, 2020 at 11:49
1
  • Sorry my bad, I removed them with regex in my code. Will change the OP. Commented Jan 28, 2020 at 12:34

2 Answers 2

2

Use:

nl = [[[*x, 'Topic %s' % idx] for x in i] for idx, i in enumerate(l)]

Or use:

nl = [[x + ['Topic %s' % idx] for x in i] for idx, i in enumerate(l)]

And now:

print(nl)

Is:

[[['0.056*"googl"', 'Topic 0'], [' 0.035*"facebook"', 'Topic 0']], [['0.021*"mensch"', 'Topic 1'], [' 0.012*"forsch"', 'Topic 1']], [['0.112*"appl"', 'Topic 2'], [' 0.029*"app"', 'Topic 2']], [['0.015*"intel"', 'Topic 3'], [' 0.015*"usb"', 'Topic 3']]]
answered Jan 28, 2020 at 11:51
2
  • Hi @U10 -Forward, thanks for your answer. One more question: How would I have to change the code if the sublists looked like this: [[['0.056', 'googl']], [['0.035', 'facebook']]] ? Commented Jan 28, 2020 at 12:41
  • @gython ask a new question Commented Jan 29, 2020 at 1:26
1

You can do it with for loop

for i in range(len(l)):
 l[i][0].append(f'Topic {i}')
 l[i][1].append(f'Topic {i}')
answered Jan 28, 2020 at 11:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.